How to retrieve data from access database(.accdb) into excel using vba

前端 未结 2 1319
醉话见心
醉话见心 2021-01-06 15:04

I\'m working on Excel VBA macros and I want to retrieve data from a MS Access database (.accdb file).

I\'ve tried using below connection string and it t

相关标签:
2条回答
  • 2021-01-06 15:25

    This should do it for you. Drop the WHERE clause if you don't want to apply a filter.

    Also, set a reference to: Microsoft ActiveX Data Objects 2.8 Library

    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
    
    0 讨论(0)
  • 2021-01-06 15:42

    I've tried using below connection string and it throws runtime error '438'

    Run-time error: '438' means that the Object doesn't support this property or method..

    You are getting that error because you are mixing VB.Net with VBA

    This

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

    should be

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

    Beside the above, I guess DBFullName = "D:\Tool_Database\Tool_Database.mdb" is a typo from your end as you are using .Accdb?

    0 讨论(0)
提交回复
热议问题