繁体   English   中英

调用时数组引发错误

[英]Array throws error when called

我正在根据范围的值创建数组,但是当尝试从数组中获取值时,会出现错误。 代码是:

Dim nombre() As Variant 'Declares the array
Dim arreglo As Long 'Declares the length of the array

fin = Cells(Rows.Count, "B").End(xlUp).Row 'Gets the last column with data
nombre = Range("B3:B" & fin).Value 'Fills the array with the values within the range
arreglo = Application.CountA(nombre) 'Gets the length of the array, in this case, 52

MsgBox nombre(1) 'This throws an error

我认为在用值填充排列时会出现问题。

先感谢您。

除非Range恰好包含1个单元格, Range.Value始终是2D Variant数组。 如果仅涉及1个单元格,则Variant将保留该值。 因此,除非您知道要处理的单元不止一个,否则不能假设您一直在获取数组。

您永远不会直接通过简单的Range.Value调用获得一维数组。

您可以使用IsArray函数确定要查看的是数组还是单个值:

Dim nombre As Variant ' don't declare as an array: let the variant hold an array instead
nombre = myRange.Value

If IsArray(nombre) Then
    'nombre is a 2D array
    If Not IsError(nombre(1, 1)) Then MsgBox nombre(1, 1)
Else
    'nombre contains a single value - possibly an error that can't be coerced into a String
    If Not IsError(nombre) Then MsgBox nombre
End If

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM