Save file PDF, if exist add number

Infine

Board Regular
Joined
Oct 16, 2019
Messages
93
Office Version
  1. 365
Platform
  1. Windows
Hello,

I am saving Excel files to PDF and everything works. However, I want to add that if the file exists already it should add 1 number. Does anyone know how do do a "check" if it exists and add "n +1" or something?

Here is the code I am using:

VBA Code:
'Create and assign variables
Dim saveLocation As String
saveLocation = "Y:\UTFLYTT\" & varDepot & ".STF.pdf"

'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=saveLocation

n = 0
Like IF Y:\UTFLYTT\" & varDepot & ".STF.pdf exists, Then Y:\UTFLYTT\" & varDepot & ".STF ". N+1 .".pdf
and if that also exists (n = 1. then do n=2 etc)
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
Hi Infine,
try this code
VBA Code:
Sub TEST()
'Create and assign variables
Dim saveLocation As String

saveLocation = "Y:\UTFLYTT\" & varDepot & ".STF.pdf"

'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=GetNextAvailableName(saveLocation)

End Sub

Function GetNextAvailableName(ByVal strPath As String) As String

    With CreateObject("Scripting.FileSystemObject")

        Dim strFolder As String, strBaseName As String, i As Long
        strFolder = .GetParentFolderName(strPath)
        strBaseName = .GetBaseName(strPath)
      
        Do While .FileExists(strPath)
            i = i + 1
            strPath = .BuildPath(strFolder, strBaseName & " " & i & ".pdf")
        Loop

    End With

    GetNextAvailableName = strPath

End Function
 
Upvote 0

Forum statistics

Threads
1,214,591
Messages
6,120,432
Members
448,961
Latest member
nzskater

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top