52

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?

1
  • 3
    Sometimes the ByRef keyword helps as well: Function test(ByRef arr() As Variant) Commented Jul 12, 2020 at 19:21

2 Answers 2

54

This seems unnecessary since the Array() function documentation clearly states that the function returns a Variant type, but VBA is a strange place. If you declare an array variable (of type Variant), then set it using Array() you can then successfully pass the variable into your function.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The dude abides
Well, I guess I've seen something every bit as stupefying as you can see in any of those other places, and in English, too.
34

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")

1 Comment

The reference for ParamArray is learn.microsoft.com/en-us/office/vba/language/concepts/… Interesting that VBA doesn't even highlight ParamArray or change the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.