我正在尝试填充一个数组,但是在每次迭代时增加了dim 1的元素大小,但是得到了#34;下标超出范围的消息"当我尝试
时ReDim Preserve sArray(1 To jTotal, 1 To UBound(sArray, 2))
有什么想法吗?
Dim j As Integer, jTotal As Integer
Dim eCount As Integer
ReDim sArray(1, 6)
For j = 1 To Application.Session.AddressLists.Item(AddList).AddressEntries.Count
On Error GoTo Err
If VBA.InStr(1, Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).GetExchangeUser.Department, _
fFilter, vbTextCompare) > 0 Then
jTotal = jTotal + 1
' '--> Redimensioning the array
ReDim Preserve sArray(1 To UBound(sArray, 1), 1 To UBound(sArray, 2))
'ReDim Preserve sArray(1 To jTotal, 1 To UBound(sArray, 2))
sArray(jTotal, 1) = j
sArray(jTotal, 2) = Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).Name
sArray(jTotal, 3) = Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).GetExchangeUser.Alias
sArray(jTotal, 4) = Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).GetExchangeUser.PrimarySmtpAddress
sArray(jTotal, 5) = Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).GetExchangeUser.BusinessTelephoneNumber
sArray(jTotal, 6) = Application.Session.AddressLists.Item(AddList).AddressEntries.Item(j).GetExchangeUser.Department
If Err.Number > 0 Then eCount = eCount + 1
End If
Next j
答案 0 :(得分:2)
正如前面提到的in the comments,你只能调整数组的最后一个维度(这是你的例子中的第二个维度)
另外,请注意:ReDim sArray(1, 6)
。它会创建一个维度为 (0 to 1, 0 to 6)
而不是(1 to 1, 1 to 6)
的数组。因此,Redim Preserve sArray(1 to 1, 1 to 6)
仍然无法正常工作,因为您将再次调整第一个维度的大小。
将数组重新标注为:
Sub Test()
Dim sArray As Variant
ReDim sArray(1 To 1, 1 To 6)
ReDim Preserve sArray(1 To 1, 1 To 7)
End Sub
答案 1 :(得分:0)
尝试使用Collection:
重写代码Dim sArray As New Collection
使用
添加新元素sArray.Add(item)
您永远不需要对集合使用redim。它是自动处理。 谷歌在 VBA Collection 上获取更多信息。