【发布时间】:2018-11-08 18:59:39
【问题描述】:
对 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("'Variable.xlsm'!.getNum") -
谢谢,@PatricK。我尝试按照您的描述更改代码,但收到错误“无法运行宏 ''variable.xlsm'!.getNum'。此工作簿中可能没有该宏,或者所有宏都可能被禁用。”代码:800A03EC。在前 2 个 Wscript.Echo 窗口之后。我验证在 Excel 电子表格中启用了宏,但仍然遇到错误
-
您的宏是在工作表中还是在模块中?如果宏不在模块中,您可能需要明确引用工作表名称。