3

Can anyone explain why this VBA function terminates on the line that defines MyArray ?

Function FindEndPinyin2(Rge As Range) As Integer

Dim MyArray() As String

MyArray = Array("cat", "dog")

FindEndPinyin2 = 2

End Function

The function, simply exits and returns a #Value! error once it reaches the line MyArray = Array( "Cat", "Dog") I realize this function doesn't do anything meaningful. It's a simplified example. Thanks in advance

3
  • What language is this? Please tag appropriately. Commented May 7, 2017 at 2:10
  • Is it Visual Basic? Commented May 7, 2017 at 2:11
  • Yes it's VBA. Sorry, I didn't mention that because I thought this was a VBA only area. I've now updated the post. Commented May 7, 2017 at 2:25

1 Answer 1

4

VBA does not convert a Variant Array into a Typed Array. You should choose either and work with it.

Dim MyArray() As String ' <--- MyArray is a TYPED array
MyArray = Array("cat", "dog") ' <-- Type Mismatch

Array(...) is a VBA function that returns a Variant Array. As a result, you cannot do this assignment that converts a variant array into a typed array, even if the elements inside the Variant Array are all of the appropriate type (String in your case).

If you insist to do this conversion you will need a loop that fill the typed array element-by-element. Much simpler is to declare MyArray as a variant array, or just as a variant:

Dim MyArray
' Also works: Dim MyArray()
' Also works: Dim MyArray() As Variant

MyArray = Array("cat", "dog")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That makes sense.
At least since Excel 2007, it is possible to assign the result of Array() to a typed array. But not if the Variant array comes from elsewhere as an argument.

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.