根据可变条件访问导出查询到电子表格?

时间:2014-01-08 16:29:56

标签: sql vba ms-access export

我有一个带按钮的表单,2个组合框作为过滤器,以及3个用于排序的组合框。此按钮成功打开一个报告(trndOTRpt,其数据来自查询trndOTQry),其条件可以根据可以选择的任何排序条件进行选择和排序。我将命令更改为导出驱动查询trndOTQry

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, _
"trndOTQry", _
"\\es3.com\dfsroot$\YK_Share\office_public\D2S\D2S\D2S_Scorecard\OTTest.xls"

这很有效。但现在我想应用相同的VBA代码来过滤/排序此查询,就像我对报告所做的那样。以下是整篇文章:

(肉和土豆位于底部,注意原始脚本中已注释掉的代码以打开报告。我只是为上述TransferSpreadsheet操作做了补充。)

Private Sub SupervisorsGo_Click()

Dim strWhereCondition As String
Dim strSupervisor As String
Dim strPosition As String
Dim varItem As Variant

For Each varItem In Me.SupervisorCombo.ItemsSelected
    strSupervisor = strSupervisor & ",'" & Me.SupervisorCombo.ItemData(varItem) _
    & "'"
Next varItem
If Len(strSupervisor) = 0 Then
    strSupervisor = "Like '*'"
Else
    strSupervisor = Right(strSupervisor, Len(strSupervisor) - 1)
    strSupervisor = "IN(" & strSupervisor & ")"
End If
For Each varItem In Me.PositionCombo.ItemsSelected
    strPosition = strPosition & ",'" & Me.PositionCombo.ItemData(varItem) _
    & "'"
Next varItem
If Len(strPosition) = 0 Then
    strPosition = "Like '*'"
Else
    strPosition = Right(strPosition, Len(strPosition) - 1)
    strPosition = "IN(" & strPosition & ")"
End If
strWhereCondition = "[supervisor] " & strSupervisor & _
                " AND [position] " & strPosition
If Me.cboSortOrder1.Value <> "Not Sorted" Then
        strSortOrder = "[" & Me.cboSortOrder1.Value & "]"
        If Me.cmdSortDirection1.Caption = "Descending" Then
            strSortOrder = strSortOrder & " DESC"
        End If
        If Me.cboSortOrder2.Value <> "Not Sorted" Then
            strSortOrder = strSortOrder & ",[" & Me.cboSortOrder2.Value & "]"
            If Me.cmdSortDirection2.Caption = "Descending" Then
                strSortOrder = strSortOrder & " DESC"
            End If
            If Me.cboSortOrder3.Value <> "Not Sorted" Then
                strSortOrder = strSortOrder & ",[" & Me.cboSortOrder3.Value & "]"
                If Me.cmdSortDirection3.Caption = "Descending" Then
                strSortOrder = strSortOrder & " DESC"
                End If
            End If
        End If
    End If
Debug.Print strWhereCondition
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, _
"trndOTQry", _
"\\es3.com\dfsroot$\YK_Share\office_public\D2S\D2S\D2S_Scorecard\OTTest.xls"
'    DoCmd.OpenReport "trndOTRpt", View:=acViewPreview, _
'    WhereCondition:=strWhereCondition
    With Queries![trndOTQry]
        .OrderBy = strSortOrder
        .OrderByOn = True
    End With
End Sub

这失败了。当原始代码转到With Reports![trndOTRpt]时,我得到运行时错误424:强制With Queries![trndOTQry]所需的对象。我觉得我已经适当调整了所有参考文献 - 为什么不在这里确认对象?

我的目标是根据表单中选择的过滤器/排序导出trndOTQry

0 个答案:

没有答案