当一个特定的表单加载时,我需要从一个表中获取一个不同的位置列表,最终的目标是将它们显示给用户(虽然宝贝步骤,但我会达到这个目的)。
下面的代码不会产生错误,但是当我尝试遍历查询返回的记录集时,我得到一个与整数i
相关的错误。
运行时错误' 6':溢出
我已对该查询进行了测试,但它确实返回了我期望的结果,因此我认为我对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
答案 0 :(得分:1)
感谢@Arvo评论说我忘记了我的do
循环中的下一条记录。
在循环中添加RS.MoveNext
解决了问题。
Do Until RS.EOF = True
locations(i) = RS![AD Location]
i = i + 1
ReDim Preserve locations(i)
RS.MoveNext
Loop
答案 1 :(得分:1)
如果我没有遗漏某些内容,您可以使用 GetRows :
Dim locations As Variant
RS.MoveLast
i = RS.RecordCount
RS.MoveFirst
locations = RS.GetRows(i)
答案 2 :(得分:0)
你似乎知道自己在做什么,所以我的问题可能毫无意义,因为我确信你有充分的理由,但是......你为什么要将记录集值填充到数组中?...或者更具体地说你最后是向用户显示结果吗?
我问,因为将SQL语句绑定到控件(子窗体,组合框,列表框等)而不是像执行操作那样迭代记录似乎要简单得多。但是,正如我所说,我想你有理由这样做。