VBA DAO 访问 Excel 2010 像数据库

VBA DAO Accessing Excel 2010 like database

我正在尝试使用 DAO 将一些 VBA 写入 Excel 2010。我希望能够像访问数据库一样访问 excel 2010 工作簿。我正在尝试打开工作簿而不是 mdb 文件。有什么方法可以将 DAO 与 excel 工作簿而不是实际数据库一起使用?

Dim db As Database
Dim rst As Recordset
Dim SQL As String

SQL = "SELECT * From [DataSheet$]"

Set db = OpenDatabase(ThisWorkbook.FullName)
Set rst = db.OpenRecordset(SQL)

'displays the first record and first field
MsgBox rst.Fields(0)

'close the objects
rst.Close
db.Close

'destroy the variables
Set rst = Nothing
Set db = Nothing

我从这里借用了代码http://www.excel-spreadsheet.com/vba/dao_ado.htm

我解决了我的问题。使用下面的代码,您可以访问 excel 文件并将其视为数据库。

Option Explicit

Private Sub btnConnect_Click()
  Dim dataConection As New ADODB.Connection
  Dim mrs As New ADODB.Recordset
  Dim SQL As String
  Dim DBPath As String
  Dim connectionString As String

  DBPath = ThisWorkbook.FullName 'Refering the sameworkbook as Data Source

  'You can provide the full path of your external file as shown below
  connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

  'Open connection
  dataConection.Open connectionString

  'Create SQL query
  SQL = "SELECT * From [DataSheet$]"

  'Open record set (query or table, connection)
  mrs.Open SQL, dataConection

  Do While Not mrs.EOF
    Debug.Print "  " & mrs!Name
    mrs.MoveNext
  Loop

  mrs.Close

  'Close Connection
  dataConection.Close
End Sub

实际上,您 可以 通过扩展 DAO.OpenDatabase():

的参数使用 DAO 连接到 Excel 工作簿
Dim conn As Object, db As Object, rst As Object

Set conn = CreateObject("DAO.DBEngine.120")  

' EXCEL OLDER VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xls", False, True, "Excel 8.0;HDR=Yes;")

' EXCEL CURRENT VERSION
Set db = conn.OpenDatabase("C:\Path\To\Excel_Workbook.xlsx", False, True, "Excel 12.0 Xml;HDR=Yes;")

Set rst = db.OpenRecordset("SELECT * FROM [SheetName$]")

MsgBox rst.Fields(0)

rst.Close
db.Close

Set db = Nothing
Set conn = Nothing
Set rst = Nothing