Hi all!
I am trying to create code to save active workbook as file with specific name in specific folder. It works fine till Loop with creating new name if file already exists - Excel is not responding after running this macro.
What I am trying to achieve is to check if file with this name already exists in folder C:\Local\KRA. If no, then save file in this folder with name "File" and today's date in format YYYYMMDD (so it would be "File 20221026").
if file already exists, then add an version number to the name (so it would be "File 20221026 v2"). But in this case everything explodes. Any ideas how to fix it?
I am trying to create code to save active workbook as file with specific name in specific folder. It works fine till Loop with creating new name if file already exists - Excel is not responding after running this macro.
What I am trying to achieve is to check if file with this name already exists in folder C:\Local\KRA. If no, then save file in this folder with name "File" and today's date in format YYYYMMDD (so it would be "File 20221026").
if file already exists, then add an version number to the name (so it would be "File 20221026 v2"). But in this case everything explodes. Any ideas how to fix it?
VBA Code:
Private Sub CommandButton7_Click()
Dim x As Long
Dim Version As String
Dim FName As String
Saved = False
FName = "C:\Local\KRA\File " & _
Format(Date, "YYYYMMDD") & ".xlsx"
Version = " v"
x = 2
'If no files with same name exist
If Dir(FName) = "" Then
ActiveWorkbook.SaveAs Filename:=FName, _
FileFormat:=xlOpenXMLWorkbook
Exit Sub
End If
'Else create new version
Do While Saved = False
If Dir(FName) = "" Then
ActiveWorkbook.SaveAs Filename:=FName & Version & x, _
FileFormat:=xlOpenXMLWorkbook
Saved = True
Else
x = x + 1
End If
Loop
MsgBox "Saved as version " & x
End Sub