我想在几个类似的数据库上创建并运行一个预定义查询列表。
这个想法是打开数据库,运行查询,然后关闭。现在我手动创建它们中的每一个,运行然后从每个数据库中删除它们。
我不知道如何在 VBA 代码中做到这一点。谁能用一个简单的例子告诉我如何做到这一点?
You can use the Name
property for each item in your database's QueryDefs
collection to make a list of your saved queries. I think that addresses the title of your question. However the body of your question seems to ask for a lot more as far as I can tell.
You can load a string variable with the text from the SQL
property of a QueryDef
in your current database. Then use the OpenDatabase
method to open another db file, and Execute
that string there.
Public Sub RunQueryOnAnotherDb(ByVal pQuery As String, _
ByVal pRemoteDb As String)
Dim dbRemote As DAO.Database
Dim strSql As String
strSql = CurrentDb.QueryDefs(pQuery).SQL
'Debug.Print strSql
Set dbRemote = OpenDatabase(pRemoteDb)
dbRemote.Execute strSql, dbFailOnError
Debug.Print "RecordsAffected: " & dbRemote.RecordsAffected
dbRemote.Close
Set dbRemote = Nothing
End Sub
There's plenty of room to refine that one. You should add error handling for example. But, though quick & dirty, I hope it points you in a useful direction.
I tested it on my system like this, and it works with my db and query names.
Public Sub test_RunQueryOnAnotherDb()
Const cstrQuery As String = "qryTestDelete"
Const cstrRemoteDb As String = "C:\share\Access\0NewScratch.mdb"
RunQueryOnAnotherDb cstrQuery, cstrRemoteDb
End Sub