ADODB MS Access和Excel VBA Recordset返回Empty

时间:2016-11-01 10:10:56

标签: excel vba excel-vba ms-access

我在MS Access和Excel VBA宏之间建立连接,将查询中的数据导入Excel中的表格。
我的代码在这里可以正常查询 除非在特定查询中使用Like语句,否则它会将空白记录集返回给VBA 有没有人知道如何解决它?

Sub ImQry()
    Dim MyTable As ListObject        
    Dim conn As ADODB.Connection
    Dim data As ADODB.Recordset
    Dim Path As String

    Set conn = New ADODB.Connection
    Set data = New ADODB.Recordset

    Dim Qry As String
    Dim DestinationTable As String
    Dim iField As Long
    Dim UserInput As Range
    Dim TotalRecord As Long

    Set UserInput = Application.InputBox( _
                                prompt:="Please provide Information", _
                                Title:="Information Required", _
                                Type:=8)

    DestinationTable = UserInput(4)

    Set MyTable = ActiveSheet.ListObjects(DestinationTable)
    Path = UserInput(1)
    Qry = "[" & UserInput(2) & "];"
    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"

    conn.Open

    On Error GoTo closeconnection
    With data
        .ActiveConnection = conn 'specfied the connection
        .Source = "SELECT * FROM " & Qry
        .LockType = adLockReadOnly
        .CursorType = adOpenDynamic
        .Open
    End With
    On Error GoTo closerecordset

    With MyTable
        .DataBodyRange.ClearContents
        .DataBodyRange.CopyFromRecordset data
        .HeaderRowRange.ClearContents
    End With

    For Each DataField In data.Fields
        iField = iField + 1
        MyTable.HeaderRowRange(iField) = DataField.Name
    Next DataField

closerecordset:
    data.Close
    closeconnection:
    conn.Close
End Sub

0 个答案:

没有答案
相关问题