是否可以引用未保存的查询?

时间:2014-03-31 14:01:06

标签: vba access-vba

我经常将现成的查询放入Access。创建>查询设计> SQL,并将代码直接粘贴到文本窗口。 enter image description here

通常我不会在Access中保存这些查询,因为我必须尽量减少一次性临时报告的混乱。我为Access编写了一个宏,它将自动保存已建立查询的结果......

Sub qry40T_export()
'export the results of the query "qry40T" to local excel file
'prompt the user for the save location
'name the file "qry40T_output.xls"

'initialize variable type
Dim save_dir As String
save_dir = "dunno_yet"

'initialize default filename
savefile_name = "qry40T_output.xls"

'prompt user for save location
save_dir = InputBox(Prompt:="Save query export to the following directory:", Title:="Save file to:", _
Default:="F:\QUERYDATA\")

'validate user submitted
If save_dir = "" Then
    'user chose 'Cancel'
    Exit Sub
End If

'compose full save filename
fullsavefile_name = save_dir & savefile_name

'edit error treatment
On Error GoTo ErrHandler

'export the query
'overwrite "qry40T_output.xls"
DoCmd.OutputTo acOutputQuery, "qry40T", "Excel97-Excel2003Workbook(*.xls)", fullsavefile_name, False, "", , acExportQualityPrint

'success
MsgBox ("Export successful.")

'restore error treatment
On Error GoTo 0

'error handling resolution
subexit:
Exit Sub

'error handling message
ErrHandler:
MsgBox Error$
Resume subexit

End Sub

...但现在我想将此相同的过程应用于未保存的查询。那可能吗?我的猜测是代码看起来像这样:DoCmd.OutputTo acOutputQuery, OpenQuery(1), "Excel97-Excel2003Workbook(*.xls)", fullsavefile_name, False, "", , acExportQualityPrint,但我似乎无法找到正确的语法。

1 个答案:

答案 0 :(得分:1)

因为这些是“扔掉”'查询并且不需要保存,您可以每次使用相同的查询名称保存它们。

例如,您可以始终将临时查询保存为" qry40T"。然后,您的宏将始终工作并保存当时在qry40T中保存的任何查询的结果。