0

我需要将存储在 .txt 文件中的一堆表导入 Access 数据库。完成导入后,我使用 ADO 连接在数据库和 Excel 工作簿之间进行通信。我将 Access 数据库设置为压缩并在关闭时修复。

问题是,当我在导入文件后关闭数据库时,我无法在不等待任意时间的情况下使用 ADO 进行连接。当我尝试连接但失败时,访问窗口似乎已关闭。我发现我必须等待的时间与导入后数据库的大小有关。导入最大的文件集后,即使等待 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
4

1 回答 1

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
于 2013-04-29T02:40:31.580 回答