使用Excel VBA ODBC导入Microsoft Access直通查询数据

时间:2018-06-27 20:50:34

标签: excel-vba ms-access odbc pass-through vba

我正在尝试从excel vba访问SQL直通查询,并从中查询两列数据。我以前曾使用此代码连接到访问表,当我将其更改为连接到访问传递查询时,它在rs.MoveFirst命令上给了我错误消息“此类型的对象不支持操作”。 / p>

如果我在阅读时注释掉它是默认的,则不需要它,添加一串.List项(但不是第一个)后,出现“无法设置List属性。键入不匹配”字样。迭代。

我需要使用其他记录集命令吗?我认为列表属性错误是由于开始不正确而导致错误到达列表末尾吗?

感谢您的协助!

    Sub Populate_Combo_Boxes()
        On Error GoTo Err_Handler

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

        Dim rs As New ADODB.Recordset
        Set rs = New ADODB.Recordset


        cnn.Mode = adModeRead
        cnn.Open ConString

        c = 0

            'Pull Agent Listing
            rs.Open "SELECT Personnel.AgentID, Personnel.Agent " & _
                    "FROM Personnel " & _
                    "WHERE (Personnel.TermDate is Null or Personnel.TermDate <= Personnel.HireDate) ORDER BY Personnel.Agent;", _
                    cnn, adOpenForwardOnly, adLockReadOnly
            rs.MoveFirst

            With frmSubmit.cmbAgent
                .ColumnCount = 2
                .BoundColumn = 1
                .ColumnWidths = "160 pt; 0 pt"
                .Clear

                Do
                    .AddItem
                    .List(c, 0) = rs!Agent
                    .List(c, 1) = rs!AgentID 'this field is hidden
                    rs.MoveNext
                    c = c + 1
                Loop Until rs.EOF

            End With

    Exit_Handler:
            If Not (rs Is Nothing) Then
          If (rs2.State And adStateOpen) = adStateOpen Then rs2.Close
          Set rs2 = Nothing
        End If
        If Not (cnn Is Nothing) Then
          If (cnn.State And adStateOpen) = adStateOpen Then cnn.Close
          Set cnn = Nothing
        End If
        Exit Sub

    Err_Handler:
        MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
        Resume Exit_Handler
    End Sub

0 个答案:

没有答案