I try to create a code for a button in Access that opens the Save as dialog box to save a report with the predefined file name with a filter to PDF file type in which the user can manually select the desired folder.
I also used below code for a different button to save it as Excel file type, which works, but I don't get it to work for PDF.
Can you guys help me. Thanks.
Private Sub PrintButton_Click()
CurrentTime = Format(Now(), "DD_MM_YYYY hh:mm")
cmdlgOpenFile.filename = "Stock overview " & MonthMFiling & " " & YearMFiling & " " & CurrentTime & ".pdf"
cmdlgOpenFile.Filter = "PDF Files (*.pdf)|*.pdf"
cmdlgOpenFile.FilterIndex = clngFilterIndexAll
cmdlgOpenFile.DialogTitle = "Save Report As"
'this is where the dialog opens
cmdlgOpenFile.ShowSave
'returns your full file name.
filename = cmdlgOpenFile.filename
End Sub
Your code gets the filename. To output a report to PDF use this command:
DoCmd.OutputTo acOutputReport, "ReportName", acFormatPDF, filename
Replace "ReportName" with the name of the report you are using.
DOC: https://learn.microsoft.com/en-us/office/vba/api/Access.DoCmd.OutputTo
Related
(My VBA knowledge is very limited - I am self-taught! so please be gentle!)
I currently have the following against a btn to export a report to pdf but I would like Access to prompt the user to type in the file name before saving to the location. As you can see I have managed to get it to save to a certain file path - but the file name needs to be changed before it saves. I currently have the file name set to "Rename this Client invoice.pdf"
Private Sub btnSaveInv_Click()
DoCmd.OutputTo acOutputReport, "rptINVOICE", _
acFormatPDF, "C:\Users\soosi\OneDrive - VTA Services\VTA Services\ACCOUNTS\Rename this CLIENT Invoice.pdf"
End Sub
(Ideally I wanted this to pick up the client name that is a field on the form that this button sits, but I can't get that to work so this was the next best thing - BUT if anyone can help with this - this would be a huge help!)
Many thanks
Sue
I'm not an Access user, so the part to get the client name as the default filename might need tweaking, but you can try this:
Private Sub btnSaveInv_Click()
Const FOLDER_PATH As String = "C:\Users\soosi\OneDrive - VTA Services\VTA Services\ACCOUNTS\"
Dim fName As String
fName = Me.clientName.Value & " " & Me.invoiceNumber.Value '<< change as needed...
fName = InputBox("Enter the filename (do not include the '.pdf')", "Enter File Name", fName)
If Len(fName) > 0 Then
If Not fName Like "*.pdf" Then fName = fName & ".pdf"
fName = FOLDER_PATH & fName 'prepend the path
If Dir(fName, vbNormal) <> "" Then 'check if file already exists
If MsgBox("This file already exists - overwrite?", _
vbQuestion + vbYesNo) <> vbYes Then Exit Sub
End If
DoCmd.OutputTo acOutputReport, "rptINVOICE", acFormatPDF, fName
End If
End Sub
In the small section of coding the DoCmd command creates a PDF of a report "VRRrep222". I enter the "VRR#" that I need to create. After this an e-mail is created and sent.
In filename = the name of the PDF will be "VRRrep222" and today's date. I need the VRR# that I entered to pull the report to also be the number in the file name (and also the subject line in my code which I did not paste here).
Is there a way to associate the report # being pulled so that it can be added to the PDF name and subject line without having to manually enter it?
Sub SendEmail()
Dim filename As String, todaydate As String
Dim Msg As Object
Dim Supplier As String
Supplier = InputBox("Supplier E-mail?")
todaydate = Format(Date, "MMDDYYYY")
filename = Application.CurrentProject.Path & "\VRRrep222_" & todaydate & ".pdf"
DoCmd.OutputTo acReport, "VRRrep222", acFormatPDF, filename, False
Set Msg = CreateObject("CDO.Message")
With Msg
Msg.To = Supplier
Msg.From = ""
Msg.cc = ""
Msg.bcc = ""
Msg.Subject = ""
Msg.TextBody = "This is an automated email that is being sent as an ALERT only. If the disposition is RETURN TO VENDOR, you will be notified with another email."
Msg.addattachment filename
Msg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
Msg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = ""
Msg.Configuration.Fields.Update
Msg.Send
End With
Kill filename
Set Msg = Nothing
End Sub
I'm new to VBA as of yesterday.
Pulling value from report data would require report be open first. Current code doesn't do that.
Don't use dynamic parameterized query with popup prompt. Query popup inputs are poor design because input cannot be validated and cannot be referenced for other purpose, such as your requirement. Use a control on form for input of criteria parameter. Either have query parameter reference form control or apply filter to report with OpenReport method. Then code can reference that control to build file name and subject. Perhaps a combobox would be best then users can only select valid VRR#.
filename = Application.CurrentProject.Path & "\" & Me.cbxVRR & "_" & todaydate & ".pdf"
DoCmd.OpenReport "VRRrep222", acViewPreview, , "YOURfieldname=" & Me.cbxVRR, acHidden
DoCmd.OutputTo acReport, "VRRrep222", acFormatPDF, filename, False
DoCmd.Close acReport, "VRRrep222", acSaveNo
...
.Subject = Me.cbxVRR
I never use dynamic parameters in query.
I have created report in MS Access and an on_click command to save the mentioned report as a PDF on the user's desktop.
The problem is that after running this command not only save PDF version, but also prints it.
I am confused, which part of my code gives command to print whole thing?
Private Sub Oldsys_atask_isorei_Click()
'file name
ReportName = "Report_" & Format(Now, "_yyyy-mm-dd") & ".pdf"
'path to Users desktop
DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "/"
'opens report in background (without it OutputTo did not seemed to work)
DoCmd.OpenReport "rprtOldsys_isorei", acViewNormal, , , acHidden
'saves report in PDF on Users desktop
DoCmd.OutputTo acOutputReport, "rprtOldsys_isorei", acFormatPDF, DTAddress & ReportName, True
'closes opened report
DoCmd.Close acReport, "rprtOldsys_isorei", acSaveNo
End Sub
acViewNormal means print this for a report, that's the default view.
Either use acViewReport (report view) or acViewPreview (print preview) to not print the report.
I'm using Access 2010 and found the Send to Email as PDF command indispensable. However, I have a problem in that I've hidden the main ribbon from my users which means they can't actually click that button.
Can anyone tell me the VBA code that will let me PDF, save the file and email via Gmail an individual report based on a given unique ID? I am happy for the user to add the email address, subject and message body and for them to click send.
I begin with the following code, but it doesn't work.
Dim myPath As String
Dim strReportName As String
DoCmd.OpenReport "rptsuivi", acViewPreview, , "tblsuivi.[NĀ°Suivi] = '" & Me.[CompanyName] & "' "
myPath = "C:\"
strReportName = "Raport de suivi" + "-" + ".pdf"
DoCmd.OutputTo acOutputReport, acFormatPDF, , myPath + strReportName, True
DoCmd.Close acReport, "rptsuivi"
looks like you can create a macro that just runs the ribbon command
https://msdn.microsoft.com/en-us/library/office/ff862419.aspx
http://www.ribboncreator2010.de/Onlinehelp/EN/_2el0osmon.htm
you'll need to find the right idMso for the ribbon function you're trying to use.
Sub SendToEmailAsPDF()
Application.CommandBars.ExecuteMso "FileSendAsAttachment"
End Sub
Say you want to have a button that the user can click and save a copy of the current file as a PDF(Documentation):
Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF
This works fine, the user is presented with a save dialog, selects a location and the file is saved, however a few things are not correct:
The type displayed does not match what was specified in the VBA, how can this be correct? It still saves as type "PDF" without issue, even after showing "DOCX" as the file type in the "Save as Type" drop down. Also the "fileName.pdf" is not placed in the "File Name" box, its as if the dialog box is unaware of the options set in the VBA code(This same issue is also referenced in this post).
UPDATE 1
After taking a second look at my code I now realize that the SaveAs2 Method was not displaying the dialog menu, the correct version of the code(simplified) can be described as:
Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String
If selected <> 0 Then
filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If
So then the real question(I guess) is how do you get "Application.FileDialog" to display the proper type you wish to save in under the "Save as type" drop down, and this has already been answered by #PatricK. Thanks everyone for the help, I apologize for the initial confused nature of this question.
I am surprised for SaveAs2 will bring you a prompt to be honest - Only a new document and .Save will bring you that prompt.
If you want to get something similar to that prompt, you use Application.FileDialog with type msoFileDialogSaveAs.
Use this code below (perhaps as an AddIn suits more):
Option Explicit
Sub MySaveAs()
Dim oPrompt As FileDialog, i As Long, sFilename As String
Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
With oPrompt
' Find the PDF Filter from Default Filters
For i = 1 To .Filters.Count
'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
' Locate the PDF filter
If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
.FilterIndex = i
Exit For
End If
Next
' Change the title and button text
.Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
.ButtonName = "Save to PDF"
' Default name
.InitialFileName = ActiveDocument.Name
' Show the Prompt and get Filename
If .Show = -1 Then
sFilename = .SelectedItems(1)
Debug.Print "Final filename: " & sFilename
' Save the file as PDF
ActiveDocument.SaveAs2 sFilename, wdFormatPDF
End If
End With
Set oPrompt = Nothing
End Sub
Screenshot sample: