2

I have a function that returns a string array

Function getAr() As String
Dim tmpAr(3) As String
getAr(0) = "Hallo"
getAr(1) = "I"
getAr(2) = "Am"
getAr(3) = "I"
getAr = tmpAr
End Function

In a Sub I want to reassign the returned string array like

Sub test()
Dim tmpAr() As String
ReDim tmpAr(UBound(getAr))
Debug.Print tmpAr(0)
Debug.Print tmpAr(1)
End Sub

The error is

assigning to data field is not possible.

I guess that is because I have to dimension the strAr to the same dimension as the myfunc arry. But I just do not get that information.

Could anyone help me here?

2 Answers 2

3

Your function and sub both need changing:

Function getAr() As String()
    Dim tmpAr(3)              As String
    tmpAr(0) = "Hallo"
    tmpAr(1) = "I"
    tmpAr(2) = "Am"
    tmpAr(3) = "I"
    getAr = tmpAr
End Function

Sub test()
    Dim tmpAr()               As String
    tmpAr = getAr
    Debug.Print tmpAr(0)
    Debug.Print tmpAr(1)
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Did not know that tmpAr = getAr makes dimensioning of tmpAr redundant. Good to know! Thanks a lot!
2

You don't need to know the dimension to assign an array, but your code wasn't correct.

Here is my amended version :

Function getAr() As String()

Dim tmpAr(3) As String

tmpAr(0) = "Hallo"
tmpAr(1) = "I"
tmpAr(2) = "Am"
tmpAr(3) = "I"

getAr = tmpAr
End Function

Notice the String(), this is how you declare the type of a function returning an array.

Also, you were dimensionning tmpAr and tried to affect values to getAr which wasn't set and as you started, it is much easier to work with a temp variable that you'll assign to the function's output at the end of the manipulations.

And your ReDim ReDim tmpAr(UBound(getAr)) was working but did not pass the array, this how you do it tmpAr = getAr and you don't even need to use ReDim before! ;)

Sub test()
Dim tmpAr() As String
tmpAr = getAr

Debug.Print tmpAr(0)
Debug.Print tmpAr(1)

End Sub

Comments

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.