如何使用vba将数据从访问数据库(.accdb)检索到excel

时间:2016-09-02 06:15:03

标签: vba excel-vba access-vba adodb excel

我正在使用Excel VBA宏,我想从MS Access数据库(.accdb文件)中检索数据。

我尝试使用下面的连接字符串,它会抛出运行时错误'438'

   Dim cn As Object, rs As Object,DBFullName As String,Target As Range
   DBFullName = "D:\Tool_Database\Tool_Database.accdb"
   Set Target = Sheets("Sheet1").Range("A1")
   Set cn = CreateObject("ADODB.Connection")
   cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";"

   Set rs = CreateObject("ADODB.Recordset")
   rs.Open "SELECT * FROM test", cn, , , adCmdText

  For int i = 0 To rs.Fields.Count - 1
  Target.Offset(1, i).Value = rs.Fields(i).Name
  Next
  Target.Offset(1, 0).CopyFromRecordset rs
  rs.Close
  Set rs = Nothing
  cn.Close
  Set cn = Nothing

请帮助我解决错误

2 个答案:

答案 0 :(得分:2)

  

我尝试使用下面的连接字符串,它会引发运行时错误' 438'

Run-time error: '438'表示Object doesn't support this property or method..

您收到该错误是因为您正在将VB.NetVBA混合

For int i = 0 To rs.Fields.Count - 1

应该是

For i = 0 To rs.Fields.Count - 1

除了上述内容之外,我猜DBFullName = "D:\Tool_Database\Tool_Database.mdb"是您使用.Accdb时最终的拼写错误?

答案 1 :(得分:1)

这应该为你做。如果您不想应用过滤器,请删除WHERE子句。

另外,设置引用: Microsoft ActiveX数据对象2.8库

Sub Select_From_Access()
    Dim cn As Object, rs As Object
    Dim intColIndex As Integer
    Dim DBFullName As String
    Dim TargetRange As Range

    DBFullName = "C:\Users\Ryan\Desktop\Nwind_Sample.mdb"

    'On Error GoTo Whoa

    Application.ScreenUpdating = False

    Set TargetRange = Sheets("Select").Range("A1")

    Set cn = CreateObject("ADODB.Connection")
    cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DBFullName & ";"

    Set rs = CreateObject("ADODB.Recordset")
    rs.Open "SELECT * FROM [OrderDetails] WHERE [OrderID] = 10248", cn, , , adCmdText

    ' Write the field names
    For intColIndex = 0 To rs.Fields.Count - 1
    TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
    Next

    ' Write recordset
    TargetRange.Offset(1, 0).CopyFromRecordset rs

    Application.ScreenUpdating = True
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    On Error GoTo 0
    Exit Sub

End Sub