Pass array to macro function from C#

I am trying to pass an array variable as a parameter to a macro function but getting the error mismatch on calling this macro file,

My code is as follows, MACRO CODE

Sub arraydef(arr() As Variant)
    MsgBox (arr(0))
End Sub

C# Code for calling the Macro function by passing the array :

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open(Server.MapPath("\\MacroFile\\MYTEFINAL1.xlsm"));
xlApp.Visible = false;
xlApp.Run("arraydef", Countryarr);

Where Countryarr is the array that i am trying to pass

Can someone please suggest on how to pass an array to a macro file as my functionality depends on it?

Upvotes: 1

Views: 619

Answers (1)

FunThomas
FunThomas

Reputation: 29181

Basically, when passing an array of something to a subroutine in VBA, the easiest solution is to declare the parameter as Variant.

Declaring the parameter as array means that the calling routine must pass exactly that array type. If a subroutine is declared to receive an array of Long, you have to pass an array of Long. Not Integer, not Variant. The same is true if the subroutine is declared to receive an array of Variant - you have to pass an array of Variant.

Now, Variant is a kind of magical data type. A variant can be anything - even an array. When you declare a parameter as Variant and pass a Long (or a String, or...), the VBA Runtime Engine takes care about that a Variant is created, stores the content of the Long (or String or...) and keeps track about what it currently stores.

If you pass an array to that Variant, VBA stores that array in the Variant (probably only a reference) and keeps track not only about the fact that it contains an array but also about the type of the array.

However, if you declare the parameter as an array of Variant, the Runtime cannot do its magic. You tell the Runtime you will get a bunch of Variants, but then you pass a bunch of Integer. The Runtime would have to convert every single element of the array from Integer to Variant - and it simply does not do that. Instead, the VBA compiler complains, or, when calling via Application.Run, throws a "Type mismatch" runtime error.

There are some functions that can help you get information what is (currently) stored in a Variant: IsArray tells you if the Variant contains an error, and VarType will give you the information about the type (for more information about VarType, see https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function). LBound and Ubound will give you the size of an array. The only thing you cannot get is the information about the dimensions of an array. In the rare case you don't know about the number of dimensions, https://stackoverflow.com/a/6902088/7599798 can give you a solution.

Upvotes: 1

Related Questions