对 VBscript 和 VBA 相当陌生...希望得到一些帮助,并且这是一个简单的答案...
我正在从 VBscript 调用 Excel VBA 中的宏/函数。对函数的调用应返回一个数字。在 Excel 中使用 VBA 调试,该函数似乎工作正常(在本例中,它显示值 1),但当我调用宏/函数并尝试在 VBscript 中回显该值时,它显示为“空”。
如何将 VBA 中的值返回到 VBscript?
感谢您的帮助
VBscript 代码示例:
Set excelOBJ = CreateObject("Excel.Application")
Set workbookOBJ = excelOBJ.Workbooks.Open("C:\variable.xlsm")
excelOBJ.Application.Visible = True
excelOBJ.DisplayAlerts = False
REM mostly for testing purposes
Dim returnValue
returnValue = 10
Wscript.Echo "'returnValue' value before call to macro function = " & returnValue
Wscript.Echo "'returnValue' TypeName before call to macro function = " & TypeName(returnValue)
returnValue = excelOBJ.Run("ThisWorkbook.getNum")
Wscript.Echo "'returnValue' value after call to macro function = " & returnValue
Wscript.Echo "'returnValue' TypeName after call to macro function = " & TypeName(returnValue)
excelOBJ.quit
Excel 中的 VBA 示例:
Public Function getNum()
getNum = 1
Debug.Print "getNum value = " & getNum
End Function
输出:
'returnValue' value before call to macro function = 10
'returnValue' TypeName before call to macro function = Integer
REM Inside Excel VBA editor
getNum value = 1
'returnValue' value after call to macro function =
'returnValue' TypeName after call to macro function = Empty
最佳答案
我建议您将代码移至模块(如果尚未移至模块中)。
应该更改此代码
returnValue = excelOBJ.Run("ThisWorkbook.getNum")
如果代码位于工作表中,假设您的工作表是“Sheet1”,这可能会起作用
returnValue = excelOBJ.Run("Sheet1.getNum")
否则,如果它在模块中,则只需使用模块名称
returnValue = excelOBJ.Run("Module1.getNum")
如果它通过此更改开始运行,但您没有收到任何返回值,您可以更改函数以传递返回值参数 ByRef
并以这种方式进行检查
关于vba - 从 VBA Excel 宏函数获取 VBscript 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595916/