我需要将存储在.txt文件中的一堆表导入Access数据库。完成导入后,我使用ADO连接在数据库和Excel工作簿之间进行通信。我将Access数据库设置为压缩并在关闭时进行修复。
问题是,当我在导入文件后关闭数据库时,我无法在不等待任意时间的情况下使用ADO进行连接。当我尝试连接并失败时,Access窗口似乎已关闭。我发现我需要等待的时间与导入后数据库的大小有关。导入最大的文件集后,即使等待60秒也是不够的。
有什么办法可以强制连接打开吗?如果失败了,我怎么能检查它是否已准备好连接?
以下是我正在使用的一些代码:
MDB_Address = "C:\example.mdb"
Shell "cmd /c " & Chr(34) & MDB_Address & Chr(34), vbHide
'Some code that tests if it has opened happens here
...
Set ObjAccess = GetObject("C:\example.mdb")
' Import tables here
ObjAccess.Quit
Call CloseAccess
Call Wait
mdbPath = "C:\example.mdb"
Set mdbConnection = CreateObject("ADODB.Connection")
' The line below gives a run time error. The description is "Automation error Unspecified Error"
mdbConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & mdbPath
Sub CloseAccess
' I have set up the access database to write a flag to a .txt file when a
userform closes and use this to help check if it has closed.
End Sub
Sub Wait
' Wait 5 seconds. The access window appears to be closed.
Dim nHour As Date, nMinute As Date, nSecond As Date, waitTime As Date
nHour = Hour(Now())
nMinute = Minute(Now())
nSecond = Second(Now()) + 5
waitTime = TimeSerial(nHour, nMinute, nSecond)
Application.Wait waitTime
End Sub
答案 0 :(得分:0)
以下是我最终要测试数据库是否已关闭的内容。我使用Windows API函数来获取Access数据库的进程句柄,然后获取其退出状态。
这看起来效果很好。肯定有其他方法可以实现这一点 - 我认为在目录中创建了一个ldb文件,它可能会检查它的存在。
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
'Open the data base
TaskID = Shell("cmd /c " & Chr(34) & MDB_Address & Chr(34), vbHide)
ACCESS_TYPE = &H400
hProc = OpenProcess(ACCESS_TYPE, False, TaskID)
'Some code that tests if it has opened happens here
...
Set ObjAccess = GetObject("C:\example.mdb")
' Import tables here
ObjAccess.Quit
Call CloseAccess
Sub CloseAccess()
Dim test As Long
'Test if the database has closed
Do Until lExitCode <> 259 And test <> 0
test = GetExitCodeProcess(hProc, lExitCode)
DoEvents
Loop
End Sub