问题
I have an Excel AddIn that I load from a C# file. On a spreadsheet, I am able to call functions from this AddIn without trouble, however, I am unable to do so using VBA.
Suppose the name of the addin is "ExcelAddIn" and the class in question is "Functions". In VBA, I have made available the reference (via Tools > References) and I would have expected the following to work:
Dim addin As ExcelAddIn.Functions
Set addin = New ExcelAddIn.Functions
result = addin.ArbitraryFunction(...)
But this gives me an "Object reference not set to an instance of an object" error. I am confused because calling "=ArbitraryFunction(...)" in any cell works just fine. My question is: why might the addin function fail with VBA, but otherwise works fine on the sheet?
I realize that this error suggests something on the C# side is not instantiating correctly. The argugment types for "ArbitraryFunction" are both objects and Doubles (I am quite sure this is not an issue though). While I cannot show you the code, I will describe what I think is the culprit. In "ArbitraryFunction", I try to use a "Microsoft.Office.Interop.Excel.Application" object. I suspect that I am not correctly instantiating this. As required, the C# code has a "OnConnection" function: perhaps my approaches in VBA does not trigger this function?
Any help, comments or suggestions is appreciated. For the time being, I am using Application.Evaluate() to get by, but this is far from ideal. I am trying to keep my work-stream and calculations in VBA, as I have a lot of number crunching to do.
Thanks!
Update
I tried to manually call the OnConnection
function in my C# code, using this for reference. It seems this approach is in the right direction, in so far as I no longer get the error described above. However, I am now met with the new error upon calling:
Dim connect_mode As AddInDesignerObjects.ext_ConnectMode
connect_mode = ext_cm_AfterStartup
Call addin.OnConnection(Application, connect_mode, addin, Nothing)
Which gives a rather strange error pop-up with the message "Value does not fall within the expected range". The error is strange because it does not stop the code, rather just pops-up without crashing the code. Thoughts?
来源:https://stackoverflow.com/questions/62363695/cannot-run-excel-add-in-functions