Kay*_*Kay 4 vbscript vba argument-passing
我尝试调用从VBS VBA子程序与VBS传递一个字符串变量VBA,却找不到此时,相应的语法:
'VBS:
'------------------------
Option Explicit
Set ArgObj = WScript.Arguments
Dim strPath
mystr = ArgObj(0) '?
'Creating shell object
Set WshShell = CreateObject("WScript.Shell")
'Creating File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Getting the Folder Object
Set ObjFolder = objFSO.GetFolder(WshShell.CurrentDirectory)
'Getting the list of Files
Set ObjFiles = ObjFolder.Files
'Creat a Word application object
Set wdApp = CreateObject("Word.Application")
wdApp.DisplayAlerts = True
wdApp.Visible = True
'Running macro on each wdS-File
Counter = 0
For Each objFile in objFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "DOC" Then
set wdDoc = wdApp.Documents.Open(ObjFolder & "\" & ObjFile.Name, 0, False)
wdApp.Run "'C:\Dokumente und Einstellungen\kcichini\Anwendungsdaten\Microsoft\Word\STARTUP\MyVBA.dot'!Test_VBA_with_VBS_Args" (mystr) 'how to pass Argument???
Counter = Counter + 1
End if
Next
MsgBox "Macro was applied to " & Counter & " wd-Files from current directory!"
wdApp.Quit
Set wdDoc = Nothing
Set wdApp = Nothing
'------------------------
'VBA:
'------------------------
Sub Test_VBA_with_VBS_Args()
Dim wdDoc As Word.Document
Set wdDoc = ActiveDocument
Dim filename As String
Dim mystr As String
'mystr = how to recognize VBS-Argument ???
filename = ActiveDocument.name
MsgBox "..The file: " & filename & " was opened and the VBS-Argument: " & mystr & "recognized!"
wdDoc.Close
End Sub
'------------------------
Run Code Online (Sandbox Code Playgroud)
小智 9
您需要在VBA中指定参数Sub并像在正常情况下从VBA使用它一样使用它们.
例如,我尝试了以下VBScript
dim wd: set wd = GetObject(,"Word.Application")
wd.Visible = true
wd.run "test", "an argument"
Run Code Online (Sandbox Code Playgroud)
和VBA
Sub Test(t As String)
MsgBox t
End Sub
Run Code Online (Sandbox Code Playgroud)
哪个成功,生成一个消息框.
小智 8
@ user69820答案的附录,如果参数是VBScript变量,则在调用子例程之前需要将它们转换为适当的类型:
这不起作用:
dim argumentVariable
argumentVariable = "an argument"
wd.run "test", argumentVariable
Run Code Online (Sandbox Code Playgroud)
这样做:
dim argumentVariable
argumentVariable = "an argument"
wd.run "test", CStr(argumentVariable)
Run Code Online (Sandbox Code Playgroud)
在Excel 2010,Win7SP1 x64上测试