KaliMa
KaliMa

Reputation: 2060

Excel VBA: Type mismatch when passing array

    myArray = Array("A", "B", "C", "D", "E")

    Call someSub(myArray)

...

    Sub someSub(ByRef myArray() as String) 'Error here
       'contents here
    End Sub

Type mismatch error on that second part -- what's causing it?

Upvotes: 4

Views: 39574

Answers (3)

Jae Carr
Jae Carr

Reputation: 1225

Should really be using option explicit and then defining all of your variables as specific types. In this case:

Option Explicit

Dim myArray(1 to 10) as String 'define the number of elements before you use it.
myArray(1) = 'A'
myArray(2) = 'B'
[etc etc]

It's a bit longer, but being type safe will make your code run faster and make it much easier to read. It also prevents errors like the one you've run into...

Upvotes: 1

KaliMa
KaliMa

Reputation: 2060

Figured it out -- had to pass it as plain Variant

Sub someSub(myArray as Variant)

Upvotes: 6

ApplePie
ApplePie

Reputation: 8942

Did you by any chance omit to use Option Explicit and then went on to not specify myArray's type ? That will make it a variant and you are saying as String which is indeed a type mismatch.

Upvotes: 11

Related Questions