将参数从VBS传递给VBA

时间:2012-12-14 09:56:58

标签: vba vbscript 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
'------------------------

2 个答案:

答案 0 :(得分:8)

您需要在VBA Sub中指定参数,并像在正常情况下从VBA使用它一样使用它们。

例如,我尝试了以下VBScript

dim wd: set wd = GetObject(,"Word.Application")
wd.Visible = true
wd.run "test", "an argument"

和VBA

Sub Test(t As String)
    MsgBox t
End Sub

成功运行,生成一个消息框。

答案 1 :(得分:8)

@ user69820答案的附录,如果参数是VBScript变量,则在调用子例程之前需要将它们转换为适当的类型:

这不起作用:

dim argumentVariable
argumentVariable = "an argument"
wd.run "test", argumentVariable

这样做:

dim argumentVariable
argumentVariable = "an argument"
wd.run "test", CStr(argumentVariable)

在Excel 2010,Win7SP1 x64

上测试