问题
I have the following code in VBA (which resides in an Excel 2007 Workbook):
Public Function Multiply(a As Double, b As Double) As Double
Multiply = a * b
End Function
If I invoke Multiply from other VBA code, it returns the correct value. However, when I call Multiply from C#:
var excel = new Application {Visible = true};
excel.Workbooks.Open(filename);
var returned = excel.Run("Sheet1.Multiply", (Double) a, (Double) b);
... the multiplication takes place (I can verify this by adding tracing to the Multiply function in VBA) but the returned value isn't available in my C# code; returned
is always null
.
Could someone please tell me how to get at the return value of Multiply from my C# code?
回答1:
Have you tried moving your function to a regular module in Excel (not a sheet module)?
回答2:
A simple example :
The test spreadsheet.xlsm has Module1
containing:
Public Function test() As String
test = "hello 1234"
End Function
With objExcel
already set to the spreadsheet...
Dim result = objExcel.Run("Module1.test")
MsgBox(result)
... produces hello 1234
in the pop-up message.
Because I had originally tested this with ? module1.test()
(successfully) in the VBA Immediate window, I was initially trying to get objExcel.Run("Module1.test()")
to work - but I was getting an error: Cannot run the macro .... The macro may not be available in this workbook or all macros may be disabled.
- removing the brackets did the trick.
回答3:
Try modifying your Multiply function to be like the code below:
Public Function Multiply(a As Double, b As Double) As Double
return a * b
End Function
来源:https://stackoverflow.com/questions/3920343/access-return-value-from-vba-function-in-net