在VBA中,可以使用OleDbConnection
對象連接到各種數據庫,包括Microsoft Access、Microsoft SQL Server、Oracle等。以下是一些OleDbConnection
對象的常見用法:
Dim conn As New OleDbConnection
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path\to\database.accdb"
conn.Open
Dim cmd As New OleDbCommand
cmd.Connection = conn
cmd.CommandText = "SELECT * FROM TableName"
Dim reader As OleDbDataReader
Set reader = cmd.ExecuteReader
While reader.Read
' 處理返回的數據
Wend
reader.Close
Dim cmd As New OleDbCommand
cmd.Connection = conn
cmd.CommandText = "INSERT INTO TableName (Column1, Column2) VALUES ('Value1', 'Value2')"
cmd.ExecuteNonQuery
conn.Close
需要注意的是,使用OleDbConnection
對象需要引用Microsoft ActiveX Data Objects
庫。可以通過在VBA編輯器中選擇"工具"菜單下的"引用"選項,然后勾選"Microsoft ActiveX Data Objects x.x Library"來添加引用。