我自己也遇到过这个错误。此处发布的解决方案均不适用于/不适用于我的情况,而且我对提供的解决方法不是 100% 满意,尤其是 geeksengine.com 解决方法,它要求您完全删除查询并重新创建它您存储在 VBA 中的代码 - 这不是一个非常通用的解决方案,如果其他人必须维护您的数据库,他们会发现自己困惑地发现他们更改的查询偶尔会恢复到其旧代码,似乎是随机的。
所以我采取了不同的方法,并编写了一个通用例程,在导出电子表格之前存储查询的 SQL 代码,然后如果代码被删除,则立即恢复代码:
Sub SafeSendQuery(QueryName As String, FileType As Variant, EmailAddresses As String, SubjectLine As String, BodyText As String)
Dim QueryCode As String
'Access has a bug where it sometimes erases the SQL code of the Query it's sending as a spreadsheet
'This stores the code in a string, so that we can restore it if it's been erased
QueryCode = CurrentDb.QueryDefs(QueryName).SQL
DoCmd.SendObject ObjectType:=acSendQuery, ObjectName:=QueryName, OutputFormat:=FileType, To:=EmailAddresses, Subject:=SubjectLine, MessageText:=BodyText, EditMessage:=True
'If the SQL code was erased, restore it
If CurrentDb.QueryDefs(QueryName).SQL <> QueryCode Then
Debug.Print "SQL Code Missing, restoring it now."
CurrentDb.QueryDefs(QueryName).SQL = QueryCode
End If
End Sub
请注意,我为 编写了此代码DoCmd.SendObject
,因为我的用户需要通过电子邮件发送电子表格,但它应该同样适用DoCmd.OutputTo
- 只需将DoCmd.SendObject
行替换为DoCmd.OutputTo
1,并根据需要修改参数。
这是调用它的子程序的样子:
Sub EmailAQuery()
Dim QueryName As String
Dim FileType As Variant
Dim EmailAddresses As String
Dim SubjectLine As String
Dim BodyText As String
QueryName = "Quarterly Figures"
FileType = acFormatXLSX
EmailAddresses = "bob@company.com; Sally@company.com"
SubjectLine = "Quarterly Figures for " & Format(Date, "mmmm yyyy")
BodyText = "Please see the Quarterly figures data for " & Format(Date, "mmmm yyyy") & ", attached."
Call SafeSendQuery(QueryName, FileType, EmailAddresses, SubjectLine, BodyText)
End Sub