VBA 您输入的对象不是有效的记录集 属性

VBA The object you entered is not a valid recordset property

好的,所以我要做的是将 ADODB.Recordset 分配给 VBA 中的列表框。我收到错误:"The object you entered is not a valid recordset property"..我在这里做错了什么?

注意:adoConn 有效并在代码中的其他地方设置。

Private Sub Form_Load()
' Error Management
On Error GoTo ErrHandler:

Dim adoRS As New ADODB.Recordset
Dim sqlStmt As String

' Create the SQL statement
sqlStmnt = "SELECT GroupName FROM tblGroups"

' Execute the statement
adoRS.Open sqlStmnt, adoConn

' Add items to the lstGroups
If (adoRS.RecordCount <> 0) Then
    Set lstGroups.Recordset = adoRS
End If

' Clean up
adoRS.Close
Set adoRS = Nothing
Exit Sub

ErrHandler:
' Clean up
If (adoRS.State = adStateOpen) Then
    adoRS.Close
End If

Set adoRS = Nothing

If Err <> 0 Then
    MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub

ADO 是这样打开的

Public Sub openConnection()
' The path to the database
Dim strDBPath As String
strDBPath = "C:\Users\Vincent\****\****\"

' The database name to connect to
Dim strDBName As String
strDBName = "Permissions_be.accdb"

' Full path to the database
Dim strDBFull As String
strDB = strDBPath & "\" & strDBName

' Instantiate an ADO object
Set adoConn = New ADODB.Connection

' Connect to database
With adoConn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Mode = adModeShareDenyNone
    .Open (strDBPath & strDBName)
End With
End Sub

更新 因此,如果有人在 Access 2010/13 上遇到此问题。 - 将列表框设置为值列表。 - 然后在 VBA 侧循环记录集

' Add items to the lstGroups
If (adoRS.RecordCount <> 0) Then

    Do While Not adoRS.EOF
        ' This is how to add two columns to one listbox if you need only
        ' one then put only the (adoRS.Fields(0))
        lstGroups.AddItem (adoRS.Fields(0) & ";" & adoRS.Fields(1))
        adoRS.MoveNext
    Loop
    lstGroups.Requery
End If

你是如何设置 adoConn 的?应该像下面这样:-

Dim cnn As ADODB.Connection 
Set adoConn= New ADODB.Connection

 With adoConn
     .Provider = "Microsoft.Access.OLEDB.10.0"
     .Properties("Data Provider").Value = "SQLOLEDB"
     .Properties("Data Source").Value = "10.******"
     .Properties("User ID").Value = "*****readonly"
     .Properties("Password").Value = "*****readonly"
     .Open
 End With

问题出在这一行

Set lstGroups.Recordset = adoRS

如果您查看文档,您会发现列表中没有 "Recordset" 属性。

ListBox 中有一个名为 List 的 属性,它接受一个变体数组。您可以从记录集中获取值并将它们放入数组中,然后放入列表中。

类似于

' Add items to the lstGroups
If (adoRS.RecordCount <> 0) Then
    lstGroups.List= adoRS.GetRows
End If

我没有对此进行任何测试,但它可能会让你走上正轨。

此外,如果您无法使用列表,此 link 有一个很好的示例,说明如何将它们一一添加 enter link description here