vba function with arguments return array code example

Example 1: vba function return array

' Function returning an array
Function ReturnsArray() As String()
    Dim returnValues(0 To 1) As String
    returnValues(0) = "a"
    returnValues(1) = "b"
    ReturnsArray = returnValues
End Function
' ----------------------------------------
Sub TestMe()
   Dim myArray() As String
   myArray = ReturnsArray()
   Debug.Print myArray(1)       ' b
End Sub

Example 2: vba function array parameter

' Sample function with array parameter
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
' ---------------------------------------------------------------
Sub TestMe()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Tags:

Vb Example