结果很少的记录集导致 'Overflow' 错误

Recordset with few results causing 'Overflow' error

加载特定表单时,我需要从 table 中抓取一个不同的位置列表,最终目标是将它们显示给用户(虽然是婴儿步骤,但我会做到这一点)。

下面的代码没有产生错误,但是当我尝试遍历我的查询 return 的记录集时,我得到一个与整数 i.[=15= 相关的错误]

Run-time error '6': Overflow

我已经测试了查询,它确实 return 我期望的结果,所以我相信我对 Recordset 对象的处理是问题所在。

我做错了什么?

Private Sub Form_load()

    Dim DB As DAO.Database
    Set DB = CurrentDb  ' Set the DB object to use

    '**
     ' Grab a recordset containing distinct locations
     '*
    Dim RS As DAO.Recordset
    Set RS = DB.OpenRecordset( _
        "SELECT DISTINCT [Active Directory].[AD Location] FROM [Active Directory]" _
    )

    Dim i As Integer: i = 0
    Dim locations() As String
    ReDim locations(0)

    '**
     ' Make an array of the locations to display
     '*
    If Not (RS.EOF And RS.BOF) Then ' Ensure that the recordset is not empty

        RS.MoveFirst    ' Move to the first record (unnecessary here, but good practice)

        '**
         ' Loop through the recordset and extract the locations
         '*
        Do Until RS.EOF = True

            locations(i) = RS![AD Location]
            i = i + 1
            ReDim Preserve locations(i)

        Loop

    Else

        '**
         ' Tell the user that there are no records to display
         '*
        Call MsgBox( _
            "Sorry, something went wrong and there are no locations to display." & vbCrLf & vbCrLf & _
                "Please ensure that the Active Directory table is not empty.", _
            vbExclamation, _
            "You'd better sit down, it's not good news..." _
        )

    End If

    RS.Close            ' Close the recordset
    Set RS = Nothing    ' Be a hero and destroy the now defunct record set

End Sub

感谢@Arvo 评论说我忘记在 do 循环中移动到下一条记录。

RS.MoveNext 添加到循环中解决了问题。

Do Until RS.EOF = True

    locations(i) = RS![AD Location]
    i = i + 1
    ReDim Preserve locations(i)
    RS.MoveNext

Loop

您似乎知道自己在做什么,所以我的问题可能毫无意义,因为我确定您有充分的理由,但是...为什么要将记录集值填充到数组中?...或更多具体你最后是怎么把结果展示给用户的?

我问是因为将 SQL 语句绑定到控件(子窗体、组合框、列表框等)中似乎比像您那样遍历记录要简单得多。但是,正如我所说,我想你这样做是有原因的。

如果我没有遗漏什么,你可以使用 GetRows:

Dim locations As Variant
RS.MoveLast
i = RS.RecordCount
RS.MoveFirst
locations = RS.GetRows(i)