vba failing to export from excel to pdf if the file already exists - vba

Sub printPdf()
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
'On Error GoTo errHandler
Set ws = Application.ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", "_"), ".", "_") _
& ".pdf"
strfolder = ThisWorkbook.Path & "\myPdfFiles"
If Len(Dir(strfolder, vbDirectory)) = 0 Then
MkDir (strfolder)
End If
strFile = strfolder & "\" & strFile
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call closews
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file " & Err & ": " & Error(Err)
Resume exitHandler
End Sub
I am having an issue with saving the pdf files.
If the file already exists in the folder and has some changes made to it the macro will crash with the debugger pointing at the openAfterPulish line and display the following runtime error.
-2214701887(80071779)
"Document not saved."
My goal is that excel should automatically overwrite the old files. Excel will prompt me if I want to overwrite the file when I am saving it manually but crashes when I run the above code.

Check if it exists and delete it. In you VBA IDE go to the tools menu and selecte references. Select "Microsoft scripting runtime"
Dim Response As Integer
Dim fs As FileSystemObject
'We can come back to here after an error.
TryAgain:
If fs.FileExists(strFile) = True Then
On Error Goto DeleteError
fs.DeleteFile(strFile, True)
End If
DeleteError:
Response = MsgBox("Error deleting file. Do you have it open? Try again?", vbYesNo)
' If statement to check if the yes button was selected.
If Response = vbYes Then
Goto TryAgain
Else
Exit sub
End If
On Error Goto 0
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call closews

Related

VBA to Create a Folder and Save as a pdf within the folder

i'm very new to VBA and have an issue.
I've received help in saving a file into a specific folder but not allowing me to overwrite the file.
Sub Autosave2()
Dim vDir
Dim strFileExists, pdfname, fileSaveName As String
Dim FSO
pdfname = ActiveSheet.Range("Q2")
vDir = "\\Reports\Internal PO Log\PO pdf's\"
If Right(pdfname, 3) = "pdf" Then
fileSaveName = vDir & pdfname
Else
fileSaveName = vDir & pdfname & ".pdf"
End If
MsgBox fileSaveName
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(fileSaveName) Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
MsgBox "PDF File Saved (CentreSoft\Reports\Internal PO Log\PO pdf's)"
Else
MsgBox "THIS PO NUMBER ALREADY EXISTS"
End If
End Sub
I now need to create a folder with the same name (Range("Q2")) and save the file as a pdf within the new folder (with the same name; PO number in this scenario)
I also need to display messages should the folder already exits thus blocking the code from running any further.
Any help would be hugely appreciated
Thanks
Is this what you want?
Sub Autosave2()
Dim vDir
Dim strFileExists, pdfname, fileSaveName As String
Dim separator As String: separator = Application.PathSeparator
Dim FSO
pdfname = ActiveSheet.Range("Q2")
vDir = "\\Reports\Internal PO Log\" & pdfname
If Dir(vDir, vbDirectory) = "" Then
'create folder
MkDir vDir
Else
MsgBox "The folder already exits thus blocking the code from running any further."
Exit Sub
End If
If Right(pdfname, 3) = "pdf" Then
fileSaveName = vDir & separator & pdfname
Else
fileSaveName = vDir & separator & pdfname & ".pdf"
End If
'MsgBox fileSaveName
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(fileSaveName) Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
MsgBox "PDF File Saved in " & vDir
Else
MsgBox "THIS PO NUMBER ALREADY EXISTS"
End If
End Sub
I've solved it :-)
Sub Autosave2()
Dim vDir
Dim strFileExists, pdfname, fileSaveName As String
Dim FSO
Dim FldrName As String
pdfname = ActiveSheet.Range("Q2")
FldrName = "\\Reports\Internal PO Log\PO pdf's\" & pdfname & "\" & pdfname
vDir = "\\Reports\Internal PO Log\PO pdf's\" & pdfname
If Dir(vDir, vbDirectory) = "" Then
'continue
Else
MsgBox "The folder already exits thus blocking the code from running any further."
Exit Sub
End If
'create folder
MkDir vDir
If Right(pdfname, 3) = "pdf" Then
fileSaveName = FldrName & ".pdf"
Else
fileSaveName = FldrName & ".pdf"
End If
'MsgBox fileSaveName
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(fileSaveName) Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
MsgBox "PDF File Saved in " & vDir
Else
MsgBox "THIS PO NUMBER ALREADY EXISTS"
End If
End Sub
Not too sure if it's the best work around but i've created a new FldrName and pointed everything towards that in the file save
Thanks so much for getting me that far.....you've been a great help

VBA code to save PDF does not work properly

I have set up a command button to save the current worksheet as a PDF file. I have played around with this code for several hours and almost got it to work properly but it seems I have disconnected some areas and cannot find my way back. Please see below for the code that I am using and the variables I am having an issue with at this point. Any help or information would be much appreciated! Thanks in advance!
Issues:
When you click 'Cancel' in the save application box, the document still tries to save.
If the file already exists:
Selecting 'Yes' to over-write does not save the document.
Selecting 'No' to over-write and renaming as another already existing document does not prompt another Question box to over-write or not. It simply over-writes the original document name.
Sub PDFFHA()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strPath = "I:\OCC FRB REMIC Reporting\Quality Control\PDFs"
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = Replace(wsA.Range("D3"), " ", "")
strName = Replace(strName, ".", "_")
strFile = "FHA" & "_" & strName & "_" & "QC" & ".pdf"
strPathFile = strPath & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If bFileExists(strPathFile) Then
lOver = MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists")
If lOver <> vbYes Then
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
Else
GoTo exitHandler
End If
End If
Else
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
With some clean-up and re-formatting.
If the file already exists, you are prompted to overwrite or not. The code only checks for the response to be vbNo since vbYes implies that strPathFile remains the same, i.e. no action needed. The loop handles a Cancel click, as well as the possibility that your new strPathFile is again an existing file.
Option Explicit
Sub PDF_FHA()
Dim wsA As Worksheet: Set wsA = ActiveWorkbook.ActiveSheet
Dim strName, strPath, strFile, strPathFile As String
On Error GoTo errHandler
' Get path
strPath = "I:\OCC FRB REMIC Reporting\Quality Control\PDFs\"
' Get and clean filename
strName = Replace(wsA.Range("D3"), " ", "")
strName = Replace(strName, ".", "_")
strFile = "FHA_" & strName & "_QC.pdf"
strPathFile = strPath & strFile
' Check if file exists, prompt overwrite
If bFileExists(strPathFile) Then
If MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists") = vbNo Then
Do
strPathFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
' Handle cancel
If strPathFile = "False" Then Exit Sub
' Loop if new filename still exists
Loop While bFileExists(strPathFile)
End If
End If
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
Firstly, turn Option Explicit on.
Follow the logic in If lOver <> vbYes Then. With the proper indenting you will see that it only handles the <> vbYes path and does not have an Else.
So, you do not actually handle the "Yes" case.
Your "No" logic only brings up a file dialog box and we don't know what you have done to test this (cancel, put new name in, just accept name as presented?). However, there is no additional question on this logic path. If you don't hit "Cancel" to the file dialog it will just save the file.

Enabling Save as automatically through vba (Without clicking save on prompt)

How can I get excel to automatically select save through VBA without manually clicking it. E.g- I have Code which selects each value on a Data Validation list and gets me to the stage below, although I have to click save each time.
I have tried adding in:
Application.EnableEvents = True
But it still only takes me to the stage on the image.
Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Cells.Range("B1") & " Period " & Cells.Range("J1")
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False, _
From:=1, _
To:=2
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
To avoid prompting:
Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Cells.Range("B1") & " Period " & Cells.Range("J1")
strFile = ThisWorkbook.Path & "\" & strFile & ".PDF"
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False, _
From:=1, _
To:=2
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub

Getting the "Do you want to overwrite the file" dialog box to show when saving with VBA

The following code saves a selected area of my excel sheet. If I try to save a file that has the same file name as one that already exists, however, it will just save the file without showing the "Do you want to overwrite the file" dialog box.
Is there a way to change this code so that it will ask if I would like to overwrite the preexisting file?
Option Explicit
Sub CreatePDF()
Dim wSheet As Worksheet
Dim vFile As Variant
Dim sFile As String
Set wSheet = ActiveSheet
sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyymmdd\_hhmm") _
& ".pdf"
sFile = ThisWorkbook.Path & "\" & sFile
vFile = Application.GetSaveAsFilename _
(InitialFileName:=sFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If vFile <> "False" Then
wSheet.Range("B2:J44").ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
End If
End Sub
One way to simulate the behavior, as suggested, is to check the selected SaveAsFilename:
Option Explicit
Sub CreatePDF()
Dim wSheet As Worksheet
Dim vFile As Variant
Dim sFile As String
Set wSheet = ActiveSheet
sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyymmdd\_hhmm") _
& ".pdf"
sFile = ThisWorkbook.Path & "\" & sFile
vFile = Application.GetSaveAsFilename _
(InitialFileName:=sFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If Dir(vFile) > vbNullString Then _
If MsgBox("Overwrite File?", _
vbExclamation + vbYesNo, "Overwrite?") = vbNo Then Exit Sub
If vFile <> "False" Then
wSheet.Range("B2:J44").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
End If
End Sub
Another alternative:
Replace:
vFile = Application.GetSaveAsFilename _
(InitialFileName:=sFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If vFile <> "False" Then
By:
With Excel.Application.FileDialog(msoFileDialogSaveAs)
Dim i As Integer
For i = 1 To .Filters.Count
If InStr(.Filters(i).Extensions, "pdf") <> 0 Then Exit For
Next i
.FilterIndex = i
.InitialFileName = sFile
.Title = "Select Folder and FileName to save"
'------------------- Bloc A -------------------------
If CBool(.Show) Then
vFile = .SelectedItems.Item(.SelectedItems.Count)
End If
If vFile <> "" Then
'------------------- Bloc A -------------------------
'----------- Or replace "Bloc A" by------------------
'If Not CBool(.Show) Then Exit Sub
'vFile = .SelectedItems.Item(.SelectedItems.Count)
'And remove the "If vFile <> "False" Then" check
'----------------------------------------------------
End With
If you selected an existing file, the overwrite message will show

VBScript to export selected portion of Excel sheet to a PDF, on one page

I currently have a VBScript that exports an entire excel worksheet to a PDF. I was wondering if it would be possible to set the script to only export the selected areas. I know this can be done manually, but I've been tasked with automating this process. If achieved, it would make the whole reporting proccess a lot easier. The VBScript that I'm currently using is:
Sub PDFActiveSheet()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Set ws = ActiveSheet
'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyymmdd\_hhmm") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF version of report has been created."
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
I've already tried replacing the "Set ws = ActiveSheet" to "Selection", and that has yielded no results. Also, as a side note, when selections are sent to a PDF, they appear on separate sheets.Is it possible to put them both on one sheet?
Thanks in advance for any help that you can offer me.
Try setting the Print Area that you want to output to PDF.