0

I'm trying to understand arrays more thoroughly. Can someone please explain to me why this does not compile:

Public Sub Test()
    Dim Names As String
    Names = Array("Brian", "Steve", "Andrea")
    Debug.Print Names(2) 'Compile error: Expected array
End Sub

and why this compiles but does not run:

Public Sub Test()
    Dim Names() As String
    Names = Array("Brian", "Steve", "Andrea") 'Run-time error '13': Type mismatch
    Debug.Print Names(2)
End Sub

but this works, even though I didn't add () (unless declaring it as type Variant makes it an array?):

Public Sub Test()
    Dim Names As Variant
    Names = Array("Brian", "Steve", "Andrea")
    Debug.Print Names(2)
End Sub

and so does this, as expected:

Public Sub Test()
    Dim Names() As Variant
    Names = Array("Brian", "Steve", "Andrea")
    Debug.Print Names(2)
End Sub
2
  • 2
    Array is type of Variant. Please, check MSDN documentation Commented Jan 3, 2018 at 19:50
  • A Variant can very well hold a pointer to an array. That makes Variant() pretty much redundant. Commented Jan 3, 2018 at 19:58

1 Answer 1

1

Well, Array function returns Variant data type containing an array. Check MSDN documentation.

Note A Variant that is not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types. Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the array elements are accessed in the same way.

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

4 Comments

Your update answered my question with the note. Thank you!
You're very welcome. If it fixes your issue, please, accept my answer as a solution.
I certainly will, but it said I had to wait 7 minutes. :) +1 for now.
OK. I'm not in rush ;)

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.