Get Data from Access Database using Excel VBA

If we can automate the process of getting data from Access database using Excel VBA then we can enhance our data analytical capabilities. Earlier we had learnt how to get data from an access database manually.

Watch the training video to learn how you can quickly and easily get data into an Excel worksheet for further analysis from a database  using VBA.

 

Watch the video on YouTube.

Here’s the complete VBA code to import data into an Excel worksheet from an Access database using VBA:

Option Explicit

Sub getDataFromAccess()
‘ Click on Tools, References and select
‘ the Microsoft ActiveX Data Objects 2.0 Library

Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer

Cells.Clear

‘ Database path info

‘ Your path will be different
DBFullName = “C:\Users\takyar\Documents\NorthWind.accdb”
‘ Open the connection
Set Connection = New ADODB.Connection
Connect = “Provider=Microsoft.ACE.OLEDB.12.0;”
Connect = Connect & “Data Source=” & DBFullName & “;”
Connection.Open ConnectionString:=Connect

‘ Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
‘ Filter Data
Source = “SELECT * FROM Orders WHERE [Shipper ID] = 3 ”
‘Source = “SELECT * FROM Customers WHERE [Job Title] = ‘Owner’ ”

.Open Source:=Source, ActiveConnection:=Connection

‘ MsgBox “The Query:” & vbNewLine & vbNewLine & Source

‘ Write field names
For Col = 0 To Recordset.Fields.Count – 1
Range(“A1”).Offset(0, Col).Value = Recordset.Fields(Col).Name
Next

‘ Write recordset
Range(“A1”).Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub