0

我在 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 秒延迟。到目前为止,它似乎正在工作。

4

1 回答 1

1

我希望这对你有帮助。

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

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

于 2013-04-15T14:34:29.360 回答