Private Sub cmdSaveAsPDF_Click()
Dim qdf As DAO.QueryDef
Dim strPathName As String
Dim rs As Recordset
Dim stDocName As String
Dim strSavedSQL As String
If Me.Dirty Then Me.Dirty = False
stDocName = "xinvoice"
Set rs = CurrentDb.OpenRecordset("SELECT orderid, tripname FROM Orders WHERE SelectedPrint;", dbOpenSnapshot)
If rs.EOF Then
MsgBox "Nothing found to process", vbCritical, "Error"
Else
CreateFolder CurrentProject.Path & "\orders"
' store the current SQL
Set qdf = CurrentDb.QueryDefs("Invoices")
strSavedSQL = qdf.SQL
While Not rs.EOF
qdf.SQL = Left(strSavedSQL, InStr(strSavedSQL, ";") - 1) & " and (orderid = " & rs!OrderID & ");"
' put in the same folder as the database
strPathName = CurrentProject.Path & "\orders\" & rs!tripname & ".pdf"
DoCmd.OutputTo acOutputReport, stDocName, acFormatPDF, strPathName
rs.MoveNext
Wend
' restore the SQL
qdf.SQL = strSavedSQL
qdf.Close
Set qdf = Nothing
End If
rs.Close
Set rs = Nothing
End Sub