Getting value in VBscript from VBA Excel Macro Function

Nic*_*k K 3 vbscript excel vba

Fairly new to VBscript and VBA... hoping for some help and that it's an easy answer...

I'm calling a Macro / Function in Excel VBA from VBscript. The call to the Function should return a number. Using VBA debug in Excel, the function appears to work properly (in this example, it displays a value of 1), but when I call the Macro / Function and attempt to echo the value in VBscript it shows as "Empty".

How can I get the value from VBA back to VBscript?
Thanks for your help

Example of VBscript code:

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
Run Code Online (Sandbox Code Playgroud)

Example of VBA in Excel:

Public Function getNum()
    getNum = 1
    Debug.Print "getNum value = " & getNum
End Function
Run Code Online (Sandbox Code Playgroud)

Output:

'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
Run Code Online (Sandbox Code Playgroud)

dbm*_*tch 5

我建议将您的代码移动到模块(如果还没有)。

应该更改此代码

returnValue = excelOBJ.Run("ThisWorkbook.getNum")
Run Code Online (Sandbox Code Playgroud)

如果代码位于工作表中,假设您的工作表是“Sheet1”,这可能会起作用

returnValue = excelOBJ.Run("Sheet1.getNum")
Run Code Online (Sandbox Code Playgroud)

否则,如果它在模块中,则只需使用模块名称

returnValue = excelOBJ.Run("Module1.getNum")
Run Code Online (Sandbox Code Playgroud)

如果它开始运行此更改,但您没有收到任何返回值,您可以更改您的函数以通过return value parameter ByRef这种方式进行检查