4
    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?

3 Answers 3

11

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.

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

3 Comments

I don't have Option Explicit listed and I did not specify the type for the array (what you see when I assign A B C D E is when I define it). What is the better alternative/what does Explicit do?
Omitting Option Explicit allows you to create variables on the fly without explicitly declaring them. This opens up bug like this one. You should put Option Explicit at the top of every VBA project. There's even an option for this.
What is the correct way to define that array above with Option Explicit?
6

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

Sub someSub(myArray as Variant)

Comments

1

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...

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.