Việc sử dụng Excel Macros (VBA) bạn có thể kết nối đến bất kỳ DB nào như SQL, Oracle, Access DB. Trong bài này chúng ta sẽ học làm thế nào để kết nối đến Access DB. Driver kết nối Access 2003 (*.mdb) có sự khác biệt với Access 2007/2010 (*.accdb).
Đối với Access 2003 Database thì Provider là: Provider=Microsoft.Jet.OLEDB.4.0.
Đối với Access 2007/2010 Database thì Provider là: Provider=Microsoft.ACE.OLEDB.12.0.
Trước khi đi đến ví dụ dưới đây, bạn phải Add reference cho ADO DB Connection. Như sau:
Nội dung chính
Làm thế nào để Add reference trong excel
- 1. Mở VB Editor(Alt+F11).
- 2. Tools –> References...
- 3. Chọn "Microsoft ActiveX Data Objects 2.0 Library". Bạn có thể chọn phiên bản 2.0 hoặc bất kỳ phiên bản nào cao hơn.
- 4. Click OK.
Kết nối với Access 2003 Database
Option Explicit
Public Const dbName = "student.mdb"
Sub ADODB_Connect()
Dim dbPath As String
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim query As String
On Error GoTo ErrorProcess
' create dpPath from current folder and dbName
dbPath = Application.ActiveWorkbook.Path & "\" & dbName
' information to connect to 2007/2010 AccessDB
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & dbPath & ";" & _
"User Id=admin;Password="
' open connection
conn.Open (strConn)
' define query
query = "SELECT * FROM student"
' execute the query
rs.Open query, conn, adOpenKeyset
' show number of records
MsgBox rs.RecordCount
' show data from AccessDB
Do Until rs.EOF
MsgBox rs.Fields.Item("name") & ", " & rs.Fields.Item("age")
rs.MoveNext
Loop
GoTo EndSub
ErrorProcess:
MsgBox Err.Number & ": " & Err.Description
EndSub:
Set rs = Nothing
Set conn = Nothing
End Sub
Kết nối với Access 2007/2010 Database
Option Explicit
Public Const dbName = "student.accdb"
Sub ADODB_Connect()
Dim dbPath As String
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim query As String
On Error GoTo ErrorProcess
' create dpPath from current folder and dbName
dbPath = Application.ActiveWorkbook.Path & "\" & dbName
' information to connect to 2007/2010 AccessDB
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath & ";" & _
"User Id=admin;Password="
' open connection
conn.Open (strConn)
' define query
query = "SELECT * FROM student"
' execute the query
rs.Open query, conn, adOpenKeyset
' show number of records
MsgBox rs.RecordCount
' show data from AccessDB
Do Until rs.EOF
MsgBox rs.Fields.Item("name") & ", " & rs.Fields.Item("age")
rs.MoveNext
Loop
GoTo EndSub
ErrorProcess:
MsgBox Err.Number & ": " & Err.Description
EndSub:
Set rs = Nothing
Set conn = Nothing
End Sub