Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array to a function in VBA?

I am trying to write a function that accepts an array as an argument. The array can have any number of elements.

Function processArr(Arr() As Variant) As String     Dim N As Variant       dim finalStr as string           For N = LBound(Arr) To UBound(Arr)         finalStr = finalStr & Arr(N)     Next N     processArr = finalStr End Function 

Here is how I try to call the function:

Sub test()     Dim fString as string     fString = processArr(Array("foo", "bar")) End Sub 

I get an error saying:

Compile Error: Type mismatch: array or user defined type expected.

What am I doing wrong?

like image 533
user2395238 Avatar asked Oct 21 '14 17:10

user2395238


People also ask

How do I pass an array to a function in Excel VBA?

If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Can a VBA function return an array?

A function in a normal module (but not a Class module) can return an array by putting () after the data type. Note that what is returned is actually a copy of the array inside the function, not a reference. So if the function returns the contents of a Static array its data can't be changed by the calling procedure.


1 Answers

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()     Dim fString As String     Dim arr() As Variant     arr = Array("foo", "bar")     fString = processArr(arr) End Sub 

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String     processArr = Replace(Join(arr()), " ", "") End Function 

If you are into the whole brevity thing.

like image 72
JNevill Avatar answered Sep 18 '22 15:09

JNevill