问题描述
我需要根据用户在表单中选择的选项来选择不同的字段。作为我正在尝试做的简化示例。
dim selection,ssql as string
If Forms![frmExport]![option1].Value = "Birthday" Then
selection = "bday"
ElseIf Forms![frmExport]![option1].Value = "Ages" Then
selection = "age"
ElseIf Forms![frmExport]![option1].Value = "Name" Then
selection = "name"
Else
selection = "*"
End If
ssql = "Select users." & selection & " from users"
DoCmd.TransferSpreadsheet acExport,acSpreadsheetTypeExcel12Xml,ssql,sPath & "user_info",True
但是我收到一个错误7871,因为尽管我可以将预定义的查询传递给TransferSpreadsheet,但显然不能以字符串形式传递它。是否可以通过对可能的查询进行约50个排列并拥有可怕的ifs巨型嵌套来实现这一目标?
解决方法
您可以通过设置导出查询的.Sql
属性来使其动态化:
Dim qd AS DAO.QueryDef
Set qd = CurrentDb.QueryDefs("myExportQuery")
qd.Sql = sSql
DoCmd.TransferSpreadsheet acExport,acSpreadsheetTypeExcel12Xml,qd.Name,sPath & "user_info",True