在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"来添加引用。