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?
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
Source: Stackoverflow.com