3

I having trouble getting this to work. I just want to return an array from a function, the code i've tried is below.

Sub 
   Dim storeData As Variant: Set storeData = getData
   Debug.Print storeData(1)
End Sub

Function getData() As Variant
   Dim arr(2) As Variant
    arr(1) = "ergreg"
    arr(2) = "1005"
    getData = arr
End Function

No errors are thrown but nothing is printed to the immediate window

4
  • 7
    Remove the Set. Commented Sep 4, 2016 at 13:55
  • This actually should give a type mismatch error. Commented Sep 4, 2016 at 13:56
  • @ChrisBull see answer below (your Debug.Print storeData(1) will only print the 2nd of the 3 elements in your array) Commented Sep 4, 2016 at 14:02
  • @Comintern I didn't have Option Explicit set, another lesson learnt Commented Sep 4, 2016 at 14:08

2 Answers 2

2

If you want to print all the array elements, you need to add a For loop to the Debug:

Dim storeData As Variant
Dim i As Long
storeData = getData

For i = LBound(storeData) To UBound(storeData)
    Debug.Print storeData(i)
Next i

Quick Note: Dim arr(2) As Variant , means arr has 3 elements (starting from 0), you are assigning values only to the second and third elements.

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

1 Comment

Thanks for replying, I have the base set as 1. And i don't need to print all the values, just needed the one for now.
-1

My mistake - Thanks @GSerg for finding it.

Just need to remove the 'Set'. So simple

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.