7

我尝试从 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
'------------------------
4

2 回答 2

11

您需要在 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

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

于 2012-12-14T12:25:31.033 回答
10

@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 上测试

于 2014-07-10T22:08:26.223 回答