Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access return value from VBA Function in .NET?

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?

like image 844
Duncan Bayne Avatar asked Oct 13 '10 02:10

Duncan Bayne


People also ask

How do you return a value from a VBA function?

To return a value using the Return statementPut a Return statement at the point where the procedure's task is completed. Follow the Return keyword with an expression that yields the value you want to return to the calling code. You can have more than one Return statement in the same procedure.

Can a VBA sub return value?

Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures CAN be called without a call keyword. Sub procedures are always enclosed within Sub and End Sub statements.

Can a sub return a value in VB net?

Sub procedures and property Set procedures cannot return values.

What is the method for returning more than one values from a function in VBA?

Use pass by reference (ByRef)


1 Answers

Have you tried moving your function to a regular module in Excel (not a sheet module)?

like image 134
Tim Avatar answered Oct 01 '22 11:10

Tim