我对vba很新。所以,一个简单的问题。在工作表中,我有单元格填充整数。比如,单元格A1到E1。我想将数据存储在一个数组中,然后解决特定的值。运行下面的代码有一个错误"下标超出范围"。我究竟做错了什么?提前谢谢。
Sub bounds()
Dim Arr() As Variant
Arr = Range("A1:E1")
Debug.Print Arr(1)
End Sub
答案 0 :(得分:1)
尝试下面的代码(如果你想使用一维数组):
Sub bounds()
Dim Arr() As Variant
Dim i As Long
' use transpose to read the range to 1-D array
Arr = Application.Transpose(Application.Transpose(Range("A1:E1")))
' loop through all elements in array
For i = LBound(Arr) To UBound(Arr)
Debug.Print "Arr index " & i & " value is " & Arr(i)
Next i
End Sub
答案 1 :(得分:0)
更简单的替代方法是枚举值,因为它也适用于多维数组:
Dim arr(), v ' As Variant is optional
arr = [A1:E1]
For Each v in arr
Debug.Print v
Next