Private Sub lblHeaderItem3_Click()
'On Error GoTo HandleError
Dim db As DAO.Database
Dim frm As Form 'reference to the NavPaneFields subform
Dim qry As DAO.QueryDef 'reference to the NavPaneFields subform recordSource
'new SQL and original SQL strings. need the original because it was saving the new SQL
Dim strSQL, strOriginalSQL As String
'portions of the SQL string containing the strings in the filter & orderBy properties
'of the NavPaneFields subform
Dim WHEREclause, OrderByClause As String
Set db = CurrentDb
Set frm = Forms!frmMainFunctions.NavPaneFields.Form
Set qry = db.QueryDefs(frm.RecordSource)
strOriginalSQL = qry.SQL
strSQL = qry.SQL
'build the SQL WHERE clause from the NavPaneFields subform's Filter property
'if Filter clause is empty do nothing, if not, then strip the query name from the fields
WHEREclause = IIf(IsNull(frm.Filter) Or Len(frm.Filter) = 0, "", Replace(frm.Filter, qry.Name & ".", ""))
'add the filter contents to a valid SQL where clause
WHEREclause = "WHERE " & IIf(Len(WHEREclause) = 0, "", WHEREclause & " AND ")
'build the SQL ORDERBY clause from the NavPaneFields subform's OrderBy property
'if no order by, finish the SQL by adding semi colon, if not add ORDERBY from form then semi-colon
OrderByClause = IIf(IsNull(frm.OrderBy) Or Len(frm.OrderBy) = 0, ";", ", " & frm.OrderBy & ";")
'insert the new clauses into the RecordSource query's SQL
'replace old where clause with newly constructed one
strSQL = Replace(strSQL, "WHERE ", WHEREclause)
'add the order by clause on to the end
strSQL = Replace(strSQL, ";", OrderByClause)
qry.SQL = strSQL
'export to excel
DoCmd.OutputTo acOutputForm, qry.Name, acFormatXLS, , True
'restore original SQL to the query so that it is left unmodified
qry.SQL = strOriginalSQL
ExitSub:
'On Error Resume Next
qry.Close
db.Close
Set db = Nothing
Set frm = Nothing
Set qry = Nothing
Exit Sub
HandleError:
MsgBox Err.Description
GoTo ExitSub
End Sub