Skip to content

Instantly share code, notes, and snippets.

@giobyte8
Created November 8, 2014 21:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giobyte8/0d98fb9e01b89a3cc6e2 to your computer and use it in GitHub Desktop.
Save giobyte8/0d98fb9e01b89a3cc6e2 to your computer and use it in GitHub Desktop.
VBA Connect to Access DB From Excel
Sub DBGetUsers()
Dim DBLearningVBA As Database
Dim RSUsers As Recordset
Dim dbPath As String
Dim dbName As String
dbPath = "C:\Users\Giovanni\Documents\"
dbName = "LearningVBA.mdb"
Set DBLearningVBA = OpenDatabase(dbPath & dbName) 'Open database
Set RSUsers = DBLearningVBA.OpenRecordset("USERS", dbOpenTable) 'Open RecordSet . 'USERS' Table
Dim row As Integer
row = 16
' Display rows in Worksheet 1
Do While Not RSUsers.EOF
Worksheets(1).Range("A" & row).Value = RSUsers.Fields(0)
Worksheets(1).Range("B" & row).Value = RSUsers.Fields(1)
Worksheets(1).Range("C" & row).Value = RSUsers.Fields(2)
Worksheets(1).Range("D" & row).Value = RSUsers.Fields(3)
RSUsers.MoveNext
row = row + 1
Loop
RSUsers.Close
DBLearningVBA.Close
End Sub
@giobyte8
Copy link
Author

giobyte8 commented Nov 8, 2014

You should activate Microsoft DAO from Tools -> References in VBA Editor.
Ensure that DB File name and path be right.

Table USERS:

ID AUTONUMERABLE
FIST_NAME TEXT
LAST_NAME TEXT
EMAIL TEXT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment