Excel VBA:传递数组时类型不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13749599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:32:42  来源:igfitidea点击:

Excel VBA: Type mismatch when passing array

excelvbaexcel-vba

提问by KaliMa

    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?

在第二部分输入不匹配错误——是什么原因造成的?

回答by ApplePie

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

您是否有机会忽略使用Option Explicit然后继续不指定 myArray 的类型?这将使它成为一个变体,并且您说as String这确实是类型不匹配。

回答by KaliMa

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

想通了 - 不得不将它作为普通的 Variant 传递

Sub someSub(myArray as Variant)

回答by Jay Carr

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

它有点长,但类型安全会让你的代码运行得更快,更容易阅读。它还可以防止您遇到的错误......