I have the below vba to export a report from access. It works great but I was looking for help baking in the reportname and filename lines. Whenever I copy this code to use in a different report, these two fields need to be changed. I would love if the reportname just automatically uses the report's name that the VBA is in (if that makes sense). Also, it'd be great if the filename could be based off a label field in the report (the field is titled lblReportName).
Any suggestions?
Code:
Private Sub btnExportReport_Click()On Error GoTo ErrHandler
Dim reportName As String
Dim fd As Object
Dim filename As String
reportName = "rptAnnualComparsionQUARTER"
Set fd = Application.FileDialog(2)
filename = "Annual Comparsion by Quarter" & " " & Format(Date, "mm.dd.yyyy") & ".pdf"
With fd
.Title = "Save to PDF"
.InitialFileName = "\Documents\" & filename
If .Show = -1 Then
filename = fd.SelectedItems(1)
If InStr(filename, ".") = 0 Then
filename = filename & ".pdf"
ElseIf Right(filename, 4) <> ".pdf" Then
k = InStrRev(filename, ".") - 1
filename = Left(filename, k)
filename = filename & ".pdf"
End If
DoCmd.OutputTo acOutputReport, reportName, acFormatPDF, filename
MsgBox "Report saved to " & filename
End If
End With
ExitHandler:
Set fd = Nothing
Exit Sub
ErrHandler:
If Err.Number = 2501 Then
MsgBox "Access cannot save this PDF because a PDF with the same name is currently open. Exit out of the PDF and then export again."
Else
MsgBox "Error #" & Err.Number & " - " & Err.Description, , "Export Error"
End If
Resume ExitHandler
End Sub