【问题标题】:VBA DAO Accessing Excel 2010 like databaseVBA DAO 访问 Excel 2010 类数据库
【发布时间】:2018-07-24 14:17:01
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 如果您发布的代码不起作用,请解释它是如何不起作用的。 FWIW 虽然我认为您不能将 open 工作簿作为数据库访问。我认为您需要使用已关闭的工作簿(保存的文件)。已经打开的工作簿可能会被文件锁定...

标签: vba excel-2010 dao


【解决方案1】:

实际上,您可以通过扩展 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

【讨论】:

  • c'est parfait !
【解决方案2】:

我发现了我的问题。使用下面的代码,您可以访问 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

【讨论】:

  • 是的,但那是 ADO,而不是 DAO。 DAO 可以工作,但如果你不解释你遇到的问题......
  • 对不起,问题是我试图用 OpenDatabase 打开一个工作簿文件,它给了我一个应用程序错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 2011-05-09
  • 2017-03-21
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多