Hi all,
I'm trying to write VBA code to save a file as V2 if V1 already exists, or V3 if V2 already exists etc. My code creates a directory if it doesn't already exist, then saves the file in that directory:
My attempts at using a loop to check if file already exists then add a version number if it does have been unssuccessful.
Is anyone able to help?
Thanks,
I'm trying to write VBA code to save a file as V2 if V1 already exists, or V3 if V2 already exists etc. My code creates a directory if it doesn't already exist, then saves the file in that directory:
VBA Code:
' Declare variables
Dim directoryname As String
Dim filename1 As String
Dim fullfilename As String
' Set "directoryname" as folder location
directoryname = _
Application.Workbooks(1).Path & "\" & Workbooks(1).Sheets("Macro").Range("J9").Text & "\" & _
Workbooks(1).Sheets("Macro").Range("J9").Text & " SUR Reports " & _
Format(Workbooks(1).Sheets("Macro").Range("L9"), "yyyy-mm-dd") & " to " & _
Format(Workbooks(1).Sheets("Macro").Range("N9"), "yyyy-mm-dd") & "\"
' If folder location does not already exist then create it, if it does exist do nothing
If Dir(directoryname, vbDirectory) = "" Then
MkDir (directoryname)
Else
End If
' Extract and save report
ThisWorkbook.Activate
Sheets("Summary 2").Select
Sheets("Summary 2").Copy
Sheets("Summary 2").Cells.Copy
Sheets("Summary 2").Cells.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
If Workbooks(1).Sheets("Macro").Range("J9").Value = "Daily" Then
filename1 = ThisWorkbook.Sheets("Macro").Range("H9").Text & " " & ThisWorkbook.Sheets("Macro").Range("J9").Text & _
" SUR " & Format(ThisWorkbook.Sheets("Macro").Range("L9"), "yyyy-mm-dd") & ".xlsx"
Else
filename1 = ThisWorkbook.Sheets("Macro").Range("H9").Text & " " & ThisWorkbook.Sheets("Macro").Range("J9").Text & _
" SUR " & Format(ThisWorkbook.Sheets("Macro").Range("L9"), "yyyy-mm-dd") _
& " to " & Format(ThisWorkbook.Sheets("Macro").Range("N9"), "yyyy-mm-dd") & ".xlsx"
End If
ActiveWorkbook.SaveAs filename:=directoryname & filename1, FileFormat:=xlOpenXMLWorkbook
My attempts at using a loop to check if file already exists then add a version number if it does have been unssuccessful.
Is anyone able to help?
Thanks,