我想使用vbs文件作为桥接器,从Java访问Excel文件中的vba-macro。另外,我需要传输一些可变参数。
在Java中我打开这样的vbs文件(工作正常):
String strFileName = "mappe2.xlsm"; //located in the same directory
String strMacroName = "showname";
String strParameter = "Myname";
String[] command = {"wscript.exe", f.getAbsolutePath(), strFileName, strMacroName, strParameter};
Process p = Runtime.getRuntime().exec(command);
在Excel中我只是试着调用这个简单的子:
Sub showname(strName As String)
MsgBox ("The name is: " & strName)
End Sub
我的(缩短的)vbs文件看起来像这样:
Dim args, ExcelFileName, ExcelMacroName
Dim opt
Dim Command2
Set args = WScript.Arguments
ExcelFileName = args(0)
ExcelMacroName = args(1)
opt = Cstr(args(2))
Set objWbk = GetObject("E:\Mappe2.xlsm")
Command2 = ExcelFileName & "!" & "showname"
'objWbk.Application.Run Command2, "opt" 'This way it works!
objWbk.Application.Run Command2, opt 'Error: "Type conflict" occurs!
WScript.Quit
在这里,您可以看到使用静态“opt”调用宏的工作正常。但由于我将其更改为变量,我得到类型冲突的错误,我不知道为什么。我需要变量。
你能帮助我吗?
答案 0 :(得分:1)
这是假设您的sub showname(strName As String)
需要字符串作为参数。
即使你的变量opt
包含一个字符串,它的类型为Variable
要传递变量,请将opt明确地转换为字符串objWbk.Application.Run Command2, Cstr(opt)
。
答案 1 :(得分:0)
在我回答自己的问题之前,我需要等待新用户。我现在想这样做,因为阅读起来要好得多。
好吧,我找到了一个解决方法。我无法解释为什么它不适用于变量,但我将展示我的解决方案是如何工作的。如果有人能解释原因,请让我和其他人知道。
让我们一步一步来做:
这里,opt获取args(2)的值:
opt = args(2)
接下来,两者都显示相同的值(都显示在我的java方法中声明的“Myname”):
wscript.echo "opt : " & opt
wscript.echo "args(2) : " & args(2)
我不能使用opt作为变量来运行我的宏:
objWbk.Application.Run Command2, opt 'Error: Type conflict!
但如果我直接使用arguments-collection,它就可以了:
objWbk.Application.Run Command2, args(2)
对我来说现在很好,因为目前我不需要改变收到的参数;我可以简单地将它们转发到宏。但是,如果有人需要使用变量传输任何不同的值,我担心他不能这样做。如果有人知道解决方案,请告诉我!
感谢您的帮助!
答案 2 :(得分:0)
我发现将Excel方法签名更改为:
Sub showname(strName As Variant)
允许我在测试中通过opt
。不过,我真的没有一个很好的解释为什么会有效。