1

我正在尝试填充一个数组,但在每次迭代时增加了 dim 1 的元素大小,但是当我尝试时收到“下标超出范围消息”

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
4

2 回答 2

2

正如评论中提到的,您只能调整数组的最后一个维度(这是您示例中的第二个维度)

另外,请注意这一点:ReDim sArray(1, 6). (0 to 1, 0 to 6)它创建一个维度为not的数组(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
于 2018-02-20T15:39:12.363 回答
0

尝试使用 Collection 重写您的代码:

Dim sArray As New Collection

添加新元素

sArray.Add(item)

您永远不需要将 redim 与 Collection 一起使用。它是自动处理的。谷歌在VBA 集合上 获取更多信息。

于 2018-02-20T16:15:30.370 回答