Reputation: 926
I have a workbook named sth_A where A is for today's date in dd-mm-yyyy format. Almost every day I open this workbook and make changes and then I update the file's name with today's date (A).
So I created a Workbook_BeforeClose
event with intention to write some code in it, that would rename my file automatically everytime I close the file.
I used Workbook.SaveAs
method, but this preserves the old file also.
Is there a way to rename an open file, or saveas without preserving the original, or another aproach that would do what I want in an elegant way?
code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.SaveAs "sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
End Sub
also:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.SaveAs ThisWorkbook.path & "/sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
End Sub
P.S. I want the first file deleted/overwriten in any case. Not only if it has the same name with the new one.
Upvotes: 0
Views: 165
Reputation: 19857
Save your workbook and Kill
the old one (basically what @Canute said).
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim sOldName As String
sOldName = ThisWorkbook.FullName
ThisWorkbook.SaveAs ThisWorkbook.Path & Application.PathSeparator & _
"sth" & Format(Date, "dd-mm-yyyy") & ".xlsm", FileFormat:=52, CreateBackup:=False
Kill sOldName
End Sub
Upvotes: 1
Reputation: 69
Add disable alert.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "sth" & Format(Date, "dd-mm-yyyy") & ".xlsm"
End Sub
Upvotes: 0
Reputation: 69
If you want to do this in the close workbook event then,
Hope this helps.
Upvotes: 0