Hey Team,
I'm trying to create a Backup folder for a specific Excel File.
The idea is that whenever someone hits the save button it will automatically save a back up file to the a folder location of my choosing. Then it will count the number of files, keep the newest "10 lets say" and delete the oldest one. Is something like that possible?
Here is my current code. This will create backups with a time stamp. The next step is deleting the older files past the count of 10.
I'm trying to create a Backup folder for a specific Excel File.
The idea is that whenever someone hits the save button it will automatically save a back up file to the a folder location of my choosing. Then it will count the number of files, keep the newest "10 lets say" and delete the oldest one. Is something like that possible?
Here is my current code. This will create backups with a time stamp. The next step is deleting the older files past the count of 10.
VBA Code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim AWB As Workbook, BackupFileName As String, i As Integer, Ok As Boolean
On Error GoTo NotAbleToSave
Set AWB = ActiveWorkbook
'Assign full path of file along file name to variable BackupFileName
' BackupFileName = AWB.FullName
NameBase = Format(Now, "mm.dd.yyyy hh.mm")
TName = ActiveWorkbook.Name
BackupFileName = "C:\MM_Backup File\" & NameBase & " " & TName & " "
'Checking whether file is saved
'If file is not saved then saving the file
If AWB.Path = "" Then
'Displaying Save as dialog box for file saving
Application.Dialogs(xlDialogSaveAs).Show
Else
'Removing file extension from file name
i = 0
While InStr(i + 1, BackupFileName, ".") > 0
'Find the extension of file
i = InStr(i + 1, BackupFileName, ".")
Wend
If i > 0 Then BackupFileName = Left(BackupFileName, i - 1)
'Adding back up extension ".bak" with file name
BackupFileName = BackupFileName & ".bak"
Ok = False
With AWB
.Save
'Creating Backup of file
.SaveCopyAs BackupFileName
Ok = True
End With
End If
NotAbleToSave:
'Code for error handling
Set AWB = Nothing
If Not Ok Then
MsgBox "Material Master has been saved. However, The Backup Copy cannot be saved without m/Link folder setup.", vbExclamation, ThisWorkbook.Name
End If
End Sub