Home » excel » How to make unique filename when saving Excel worksheet in VBA

How to make unique filename when saving Excel worksheet in VBA

Posted by: admin May 14, 2020 Leave a comment


I have a spreadsheet that is my template that everyone accesses. The first button I want them to hit is my Macro “Save As” button that saves in the correct spot on my SharePoint.

This works great! BUT… it overwrites without warning.

I would like to 1 – make sure it never overwrites – I would prefer it cancel the process without saving over something.

Second, I would prefer that it saves it as “[predetermined name]_copy01” where 01 can go to 99 in case the button gets tapped again by someone else after the sheet is completed by the original person (thus ruining that first person’s day).

Here is my current code – how do I at least get a pop up for overwriting, and even better, get the renaming for copies (I am assuming this is some sort of “if” or “if/else” statement)

Sub Save_Workook_NewName()

Dim tillDay As Date

If Time < 11 / 24 Then    
    tillDay = Date - 1 + 11 / 24    
    tillDay = Now    
End If

Application.AlertBeforeOverwriting = True

Dim path As String
path = "https://ourcorporatesite.sharepoint.com/sites/tills/Shared%20Documents/Nightly%20Tills/"
ThisWorkbook.SaveAs FileName:=path & Format(Now(), "yy-mm-dd") & "_Tills.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, ReadOnlyRecommended:=False

End Sub
How to&Answers:

For making a unique file name, I am using the Username of the Excel user and the current time stamp. Thus, it makes sure that every user generates a different file name, always. Just make sure that the code runs more than 1 second (or add the 1 second wait in the name generator):

Public Function GenerateName() As String
    GenerateName = Format(Now(), "yyyy_mm_dd_hh_MM_ss") & "_" & Environ("Username")
End Function

In this case, if you want to save the file it is the following: 2019_11_14_22_08_50_vityata. As a bonus, it could be easily sorted by date created.

It could be called like this:

ThisWorkbook.SaveAs Filename:=Path & GenerateName & ".xlsm"