一维数组的ReDim抛出'下标超出范围'

时间:2017-05-14 14:00:56

标签: arrays vba resize

我希望通过“切断”前五个条目来重新创建一维数组,因为它们必须被移除以用于以后的逻辑。

  1. 我从查询中创建了一个记录集
  2. 我填充了一个数组recordSet()As Variant(size是147)。 现在:recordSet的大小= daoRst3的大小
  3. 我尝试删除数组recordSet的前五个元素。
  4. 代码:

    Set daoRst3 = gDB.OpenRecordset("SELECT * FROM TEST")
    
    For i = 0 To daoRst3.Fields.Count - 1
    ReDim Preserve recordSet(0 To i)
    If daoRst3.Fields(i).Value = Empty Then
        recordSet(i) = 0
    Else: recordSet(i) = daoRst3.Fields(i).Value
    End If
    Next
    
    'First five values in record set are not needed anymore.
    ReDim Preserve recordSet(5 To i - 1)
    

    最后一行

    ReDim Preserve recordSet(5 To i - 1)
    

    抛出“下标超出范围”。我已经通过调试检查了我现在是148岁。

    可能是什么问题?

    非常感谢提前!

1 个答案:

答案 0 :(得分:0)

好的,这次我明白了......

Private Sub this()

    Dim rs As DAO.Recordset

    Set rs = CurrentDb.OpenRecordset("SELECT * FROM tmpCardList")

    Dim msg As String
    Dim myArray() As String
    Dim array2() As String
    ReDim array2(0 To rs.Fields.Count - 1)
    Dim i As Long

    For i = 0 To rs.Fields.Count - 1
        Debug.Print ; rs.Fields(i).Name
        array2(UBound(array2, 1) - i) = rs.Fields(i).Name
    Next i

    ReDim Preserve array2(UBound(array2) - 5)
    ReDim myArray(0 To UBound(array2, 1))

    For i = 0 To UBound(array2, 1)
        myArray(UBound(array2, 1) - i) = array2(i)
    Next i

    rs.Close
    Set rs = Nothing

End Sub

原来你必须编写自己的自定义东西来排序数组。一点额外的箍。刚刚意识到最终输出是相反的,但你可以通过复制我的初始反转逻辑轻松“撤消”它。

最终编辑 - 这次打字更少 - WOOHOO