how can I make sure that my VBA code is not overwriting existing files while saving?
Example: I'm saving every sheet as a new workbook, and want to have v1, v2, v3 etc. With the code below I'm always overwriting the existing file, as every file I save has the same file name with "_V1" ending...
NewWbName = Left(wbSource.Name, InStr(wbSource.Name, ".") - 1)
For i = 1 To 9
'check for existence of proposed filename
If Len(Dir(wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx")) = 0 Then
wbTemplate.SaveAs wbSource.Path & Application.PathSeparator & NewWbName & "_V" & i & ".xlsx"
Exit For
End If
Next i
If i > 9 Then
'_V1.xlsx through _V9.xlsx already used; deal with this situation
MsgBox "out of options"
wbTemplate.Close False 'close template
Next wsSource
wbSource.Close False 'close source
End If
End Sub
Loop through various _Vn.xlsx variations until you find one that isn't there.
If you are going to raise the loop into double digits, perhaps
... & "_V" & Format(i, "00") & ".xlsx
would be better so that a folder sorted by name puts them in the correct order.Recommend using a date and time stamp for so many versions.
“V” & Format(date, “yyyymmdd”) & format(time, “hhmmss”) & “.xlsx”
Yes, you may still want to check for an existing file, but it’s seldom the user will submit input in less than a second