The VBA method can call the C # object method through COM InterOP. The basic method is to expose the. NET object through COM InterOP, and then you can call the. NET object method and pass the parameter. However, if the parameter contains a double array, VBA will see the following error message.
"Function or interface marked as restricted, or the function uses an automation type not supported in Visual Basic"
This problem will be solved below
VBA calls C # object Method
The C # class callableclass must inherit from the interfaceexposer interface. The interfaceexposer method is public and can be called using VBA.
// Interfaceexposer. CS
Using system;
Namespace blah
{
Public interface interfaceexposer
{
Int callablemethodsimple (double );
}
}
// Cssclass. CS
Using system;
Namespace blah
{
Public class callableclass: interfaceexposer
{
Public int callablemethodsimple (double)
{
Return (INT);
}
}
}
Important: Register com InterOP for the project. In vs 2003, select "Project Properties"-"configuration properties"-"generate", set "com InterOP registration" to true, and then compile.
VBA: Select tool reference and select COM object.
'Vba code
Public cssobject as new sendarray. callableclass 'sendarray is the project name
Dim iclass as interfaceexposer
Sub myroutine ()
Set iclass = cssobject
Dim result as integer
Result = iclass. callablemethodsimple (5.0)
End sub
Using VBA to pass a double Array
// Cssclass. CS
Using system;
Using system. reflection;
Namespace blah
{
Public class callableclass: interfaceexposer
{
...
Public int callablemethodarray (Object)
{
Double [] thisvect = loadcomobjectintodoublearray ();
Return 0;
}
Private double [] loadcomobjectintodoublearray (Object comobject)
{
Type thistype = comobject. GetType ();
Type dbltype = type. GetType ("system. Double [*]");
Double [] doublearray = new double [1];
If (thistype = dbltype)
{
Object [] ARGs = new object [1];
Int numentries = (INT) thistype. invokemember ("length", bindingflags. getproperty, null, comobject, null );
Doublearray = new double [numentries];
For (INT J1 = 0; J1 <numentries; J1 ++)
{
ARGs [0] = J1 + 1;
Doublearray [J1] = (double) thistype. invokemember ("getvalue", bindingflags. invokemethod, null, comobject, argS );
}
} // End if (thistype = dbltype)
Return doublearray;
} // End loadcomobjectintodoublearray ()
}
}
'Vba code
Public cssobject as new sendarray. callableclass 'sendarray is the project name
Dim iclass as interfaceexposer
Sub myroutine ()
Set iclass = cssobject
Dim result as integer
Dim sendarray (1 to 2) as double
Sendarray (1) = 5.2
Sendarray (2) = 7.5
Result = iclass. callablemethodarray (sendarray)
End sub