我正在尝试从excel vba获取已打开数据库的记录集。在 daoDB 变量中获取已打开数据库的引用。我的excel vba代码
Public Sub getdatafromaccess1()
Dim daoDB As DAO.Database
Dim daoQueryDef As DAO.QueryDef
Dim daoRcd As DAO.Recordset
'Here i want to reference to already opened database instead of opening
Set daoDB= OpenDatabase("C:\temp\sample.accdb")
Set daoQueryDef = daoDB.QueryDefs("Headings")
Set daoRcd = daoQueryDef.OpenRecordset
ThisWorkbook.Worksheets("w1").Range("A1").CopyFromRecordset daoRcd
End Sub
答案 0 :(得分:2)
为了维护更清晰,更易于访问的代码,将连接状态转换为全局变量是明智之举,这样您就可以在所有函数和子函数中使用该对象。
更新 - 这将在工作簿打开时保持连接。
Global daoDB As DAO.Database
Private Sub Workbook_Open()
Set daoDB = OpenDatabase("C:\temp\sample.accdb") 'Your DB connection function
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
daoDB.Close
End Sub