访问VBA DoCmd.TransferSpreadsheet运行太慢并导致运行时错误

时间:2013-04-15 14:29:59

标签: vba ms-access

我在Access中的自定义类别中有一组查询,以及一些获取查询名称并运行它们的VBA代码,然后将每个查询的结果复制到Excel电子表格上的单独选项卡。这是代码:

Private Sub Command0_Click()

Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim timestamp As String
Dim path As String

'Create the Excel spreadsheet
timestamp = Format(Now(), "yyyyMMddhhmmss")

path = "C:\Users\username\Desktop\ValidationResults" & timestamp & ".xlsx"

Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets("Sheet1")
oBook.SaveAs path
oExcel.Quit

'This gets a list of query names and puts it in a recordset
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("01 - GetValidationQueries")

'this runs each query and copies the results to a unique worksheet
Do While Not rs.EOF
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, rs("Name"), path, True, Left(rs("Name"), 2)
    rs.MoveNext
Loop

End Sub

“01 - GetValidationQueries”查询在MSysNavPaneGroupToObjects和MSysNavPaneObjectIDs表中查找,以获取自定义类别中的查询名称。

问题是,当我单击表单按钮运行此代码时,我在DoCmd行上收到以下错误:

Run-time error '3275':
Unexpected error from external database driver (1309).

如果我逐行逐步执行代码(每次点击F8)它运行正常,所以我猜测TransferSpreadsheet进程太慢了。除了在该行之后暂停,是否有更好的方法使这项工作?

编辑:使用以下代码(至少目前为止)

Public Function fnWait(intNrOfSeconds As Integer)
Dim varStart As Variant
  varStart = Timer
  Do While Timer < varStart + intNrOfSeconds
  Loop
End Function

然后在DoCmd线之前和之后,我有......

fnWait (2)

...创造2秒延迟。到目前为止似乎工作正常。

1 个答案:

答案 0 :(得分:1)

我希望这对你有所帮助。

http://p2p.wrox.com/access-vba/24421-wait-function-vba.html

我确实将它添加到我的数据库中,所以如果您需要帮助实现它,请询问。