vba VB:类型不匹配错误,数组维度 1x1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22467075/
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-12 02:23:36  来源:igfitidea点击:

VB: Type Mismatch Error, Array Dimensions 1x1

arraysvbadimensionstype-mismatch

提问by user3430878

I am trying to use a Variantdatatype to store an array of strings. This is an example of the code I am using.

我正在尝试使用Variant数据类型来存储字符串数组。这是我正在使用的代码示例。

Sub Selecto()

Dim numRows As Integer    
Dim Badger As Variant

numRows = InputBox("How many rows?", "Rows",0)
Badger = Range("C21:C"& 21 -1 + numRows).Value    

For i = 1 To UBound(Badger)
    MsgBox (Badger(i, 1))
Next

End Sub

My goal is to make it so that Badgeris an array whose length can be defined by the user running the macro via the InputBox. The code works just fine, except when the value of numRowsentered is 1 it spits out a "type mismatch error".

我的目标是使它成为Badger一个数组,其长度可以由用户通过 InputBox 运行宏来定义。代码工作得很好,除非当numRows输入的值为 1 时它会吐出“类型不匹配错误”。

The error causes the line For i=1 to UBound(Badger)to be highlighted and the error message box says that there is a "type mismatch".

该错误导致该行For i=1 to UBound(Badger)突出显示,错误消息框显示存在“类型不匹配”。

I'm guessing that for a 1-by-1 array, the data is simply stored as a string rather than as an array and that array functions like Ubound()and array index syntax like Badger(i,1)don't work. Is that the case? Is there a way to force it to recognize that variable as an array?

我猜测对于 1×1 数组,数据只是作为字符串而不是数组存储,并且数组函数Ubound()和数组索引语法之类的Badger(i,1)不起作用。是这样吗?有没有办法强制它将该变量识别为数组?

回答by haddosm

If only one value is read from the range then the variant doesn't create an array, which is why you get a type mismatch when trying to index it. Try checking if Badgeris an array with IsArray(Badger). The code below works when I use it:

如果仅从范围中读取一个值,则该变体不会创建数组,这就是在尝试对其进行索引时会出现类型不匹配的原因。尝试检查是否Badger是带有IsArray(Badger). 下面的代码在我使用时有效:

Sub Selecto()
    Dim numRows As Integer
    Dim Badger As Variant

    numRows = InputBox("How many rows?", "Rows", 0)

    Badger = Range("C21:C" & 21 - 1 + numRows).Value

    If IsArray(Badger) Then
        For i = 1 To UBound(Badger)
            MsgBox (Badger(i, 1))
        Next
    Else
        MsgBox Badger
    End If
End Sub