我在excel vba中有一个数组,我想在数组的末尾附加3个项目,但每当我运行代码时,我都会得到一个超出范围的下标。
首先,我将" rtv"数组,我想追加" class"," age"和"地址到" rtv"数组但我收到错误。
我的代码如下所示:
rtv = Split(Application.WorksheetFunction.VLookup(Name,Sheets("Properties").Range("B1:C7"), 2, False), ",")
rtv(UBound(rtv)) = "Class"
rtv(UBound(rtv) + 1) = "Age"
rtv(UBound(rtv) + 2) = "Address"
For i = LBound(rtv) To UBound(rtv)
rtv(i) = Chr(34) & rtv(i) & Chr(34) & ":" & Chr(34) & Chr(34) & ";"
Next i
这就是我声明我的数组的方式:
Dim rtv() As String
Dim i As Long
任何人都知道错误在哪里?
答案 0 :(得分:1)
在VBA
中,只需向其中添加元素,就无法增加数组的大小。该数组必须为ReDim
。如果在ReDim
期间需要保留内容,则必须使用ReDim Preserve
。
示例(使用字符串简化Application.WorksheetFunction.VLookup(Name,Sheets("Properties").Range("B1:C7"), 2, False)
)
Sub test()
Dim rtv() As String
sVLookupResult = "a,b,c"
rtv = Split(sVLookupResult, ",")
lrtvLength = UBound(rtv)
ReDim Preserve rtv(lrtvLength + 3)
rtv(lrtvLength + 1) = "Class"
rtv(lrtvLength + 2) = "Age"
rtv(lrtvLength + 3) = "Address"
For i = LBound(rtv) To UBound(rtv)
rtv(i) = Chr(34) & rtv(i) & Chr(34) & ":" & Chr(34) & Chr(34) & ";"
Next i
MsgBox Join(rtv)
End Sub