使用Excel中的VBA在Microsoft Access中打开表

时间:2018-02-02 23:03:13

标签: excel vba excel-vba

我尝试从Microsoft Access加载表格并将其粘贴到带有VBA的Excel单元格中。

我的路径正确找到我的.accdb文件并在第一个Cells(第x行).Value = statement之前发生错误。

" OpenRecordset"方法没有引用表格,让我觉得我不应该以表格的名义传递 - 或者完全使用不同的方法。

我收到错误:"运行时错误' 3265'应用程序定义或对象定义的错误

以下是我的代码:

Sub ImportAccessButton()
Dim row As Integer
Dim dbPassengerCarMileage As Database
Dim rstPassengerCarMileage As Recordset
    row = 3
    Set dbPassengerCarMileage = OpenDatabase(ThisWorkbook.Path & "\Cars.accdb")
    Set rstPassengerCarMileage = dbPassengerCarMileage.OpenRecordset("Amber")
    If Not rstPassengerCarMileage.BOF Then
        Do Until rstPassengerCarMileage.EOF
            Cells(row, 1).Value = rstPassengerCarMileage!MAKE
            Cells(row, 2).Value = rstPassengerCarMileage!Model
            Cells(row, 3).Value = rstPassengerCarMileage!VOL
            Cells(row, 4).Value = rstPassengerCarMileage!HP
            Cells(row, 5).Value = rstPassengerCarMileage!MPG
            Cells(row, 6).Value = rstPassengerCarMileage!SP
            Cells(row, 7).Value = rstPassengerCarMileage!WT
            row = row + 1
            rstPassengerCarMileage.MoveNext
        Loop
    End If
    'Close database and Cleanup objects
    rstPassengerCarMileage.Close
    dbPassengerCarMileage.Close
    Set rstPassengerCarMileage = Nothing
    Set dbPassengerCarMileage = Nothing
End Sub

1 个答案:

答案 0 :(得分:1)

它使用ADODB。 CopyFromRecordset命令加速。

Sub ImportAccessButton()

    Dim Rs As Object
    Dim strConn As String
    Dim i As Integer
    Dim Ws As Worksheet
    Dim strSQL As String

    set Ws = ActiveSheet

    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & ThisWorkbook.Path & "\Cars.accdb" & ";"

    strSQL = "SELECT * FROM Amber"

    Set Rs = CreateObject("ADODB.Recordset")
    Rs.Open strSQL, strConn

    If Not Rs.EOF Then
         With Ws
            .Range("a2").CurrentRegion.ClearContents
            For i = 0 To Rs.Fields.Count - 1
               .Cells(2, i + 1).Value = Rs.Fields(i).Name
            Next
            .Range("a" & 3).CopyFromRecordset Rs
        End With
    End If
    Rs.Close
    Set Rs = Nothing
End Sub