我正在从范围的值创建一个数组,但是当尝试从数组中获取值时,会出现错误。代码是:
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
我认为在使用值填充排列时会出现问题。
提前谢谢。
答案 0 :(得分:0)
除非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