views:

52

answers:

2

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?

A: 

Try modifying your Multiply function to code below

Public Function Multiply(a As Double, b As Double) As Double

return a * b

End Function

Amarpreet
That isn't even valid VBA. See: http://office.microsoft.com/en-in/excel-help/create-custom-functions-in-excel-2007-HA010218996.aspx
Duncan Bayne
@Amarpreet: You can't use the return keyword in VBA - you need to set the return value to the function name e.g. Multiply = a * b, which was in the original question.
Jazza
+2  A: 

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

Tim

Tim
I created a new Module, moved the Function to that, and changed "Sheet1.Multiply" to "MyModule.Multiply". Worked perfectly, thanks :-) Just one question: was this an insight you gained through experience, or is this actually documented somewhere? The information on MSDN etc. is pretty sparse for calling VBA via. interop.
Duncan Bayne