在尝试将图纸中的值分配给数组的各个元素时,如何动态调整数组的大小?在A和B列中,我有
A B
1 Houston
2 Miami
3 New York
4 Toronto
5 Los Angeles
我希望VBA确定元素的数量并根据其中有多少个元素确定数组的大小。然后,定义的数组从B列获取分配给元素的值。在下面的代码中,我尝试使用For循环来获取值并将其分配给每个元素。
这是我的代码:
Sub getNames()
Dim n As Integer 'denotes the number of elements
Dim i As Integer 'index
Dim Name() As String
Dim flag As Boolean
'Initialize values
i = 0
n = 0
flag = True
'For loop to determine number of elements
While flag = True
'check if the current cell has data in it
If Cells(i + 1, 1) <> "" Then
i = i + 1
Else
flag = False
End If
Wend
n = i
ReDim Name(n)
For i = 1 To n
Name(i) = cells(i,2).value
Next i
End Sub
但是,当尝试从单元格中分配值时,我一直收到语法错误。
答案 0 :(得分:1)
将Name
声明为变体
Dim Name as Variant
然后填写3行:
With ActiveSheet 'Should change to the sheet in question; WorkSheets("Sheet1")
Name = .Range("B1", .Cells(.Cells(.Rows.Count,1).End(xlup).Row,2)).Value
End With