简体   繁体   English

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

[英]ReDim of one-dimensional array throws 'Subscript out of Range'

I want to redim an one-dimentional array by "cutting off" the first five entries as they have to be removed for a later logic. 我想通过“切断”前五个条目来重新划分一维数组,因为它们必须被移除以用于后来的逻辑。

  1. I created a record set from a query 我从查询中创建了一个记录集
  2. I filled an array recordSet() As Variant (size is 147). 我填充了一个数组recordSet()As Variant(size是147)。 Now: size of recordSet = size of daoRst3 现在:recordSet的大小= daoRst3的大小
  3. I try to remove the first five elements of the array recordSet. 我尝试删除数组recordSet的前五个元素。

Code: 码:

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)

The last row 最后一排

ReDim Preserve recordSet(5 To i - 1)

throws "Subscript out of range". 抛出“下标超出范围”。 I already checked with debugging that i is 148 at this moment. 我已经通过调试检查了我现在是148。

What might be the problem? 可能是什么问题?

Many thanks in advance! 提前谢谢了!

Alright this time i got it... 好的,这次我明白了......

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

Turns out you have to write you own custom thing to sort the array. 原来你必须编写自己的自定义东西来排序数组。 A little bit of an extra hoop. 一点额外的箍。 Just realized the final output is reversed but you could easily "undo" that by replicating my initial reversing logic. 刚刚意识到最终输出是相反的,但你可以通过复制我的初始反转逻辑轻松“撤消”它。

Final Edit - this time with less typing - WOOHOO 最终编辑 - 这次打字更少 - WOOHOO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM