Option Explicit
Public Sub MakeArchive()
Dim ans As VbMsgBoxResult, d, yr, mn, dy
d = Weekday(Now, vbSunday)
yr = Year(Now)
mn = Month(Now)
dy = Day(Now)
If d = 4 Or d = 5 Or d = 6 Then
If CheckForArchive(ThisWorkbook.Path) = False Then
ans = MsgBox("There is no archive folder. Would you like to create one?", vbYesNo + vbQuestion, _
"Archive Not Found")
If ans = vbNo Then Exit Sub
MkDir (ThisWorkbook.Path & "\Archive")
MkDir (ThisWorkbook.Path & "\Archive\" & yr)
MkDir (ThisWorkbook.Path & "\Archive\" & yr & "\" & mn)
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Archive\" & Year(Now) & "\" & Month(Now) & "\" & _
mn & "-" & dy & ".xlsx"
End If
If CheckForRecordYear(ThisWorkbook.Path & "\Archive", yr) = False Then
MkDir (ThisWorkbook.Path & "\Archive\" & yr)
MkDir (ThisWorkbook.Path & "\Archive\" & yr & "\" & mn)
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Archive\" & Year(Now) & "\" & Month(Now) & "\" & _
mn & "-" & dy & ".xlsx"
End If
If CheckForRecordMonth(ThisWorkbook.Path & "\Archive\" & yr, mn) = False Then
MkDir (ThisWorkbook.Path & "\Archive\" & yr & "\" & mn)
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Archive\" & Year(Now) & "\" & Month(Now) & "\" & _
mn & "-" & dy & ".xlsx"
End If
If CheckForRecordDay(ThisWorkbook.Path & "\Archive\" & yr & "\" & mn, dy) = False Then
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\Archive\" & Year(Now) & "\" & Month(Now) & "\" & _
mn & "-" & dy & ".xlsx"
End If
End If
End Sub
Private Function CheckForArchive(ByVal fPath As String) As Boolean
Dim fObj As Object, fldr As Object, f As Object
Set fObj = CreateObject("Scripting.FileSystemObject")
Set fldr = fObj.GetFolder(fPath)
For Each fldr In fldr.SubFolders
If fldr.Name = "Archive" Then CheckForArchive = True: Exit Function
Next fldr
CheckForArchive = False
End Function
Private Function CheckForRecordYear(ByVal fPath As String, ByVal yr As Variant) As Boolean
Dim fObj As Object, fldr As Object, f As Object
Set fObj = CreateObject("Scripting.FileSystemObject")
Set fldr = fObj.GetFolder(fPath)
For Each fldr In fldr.SubFolders
If fldr.Name = CStr(yr) Then CheckForRecordYear = True: Exit Function
Next fldr
CheckForRecordYear = False
End Function
Private Function CheckForRecordMonth(ByVal fPath As String, ByVal mn As Variant) As Boolean
Dim fObj As Object, fldr As Object, f As Object
Set fObj = CreateObject("Scripting.FileSystemObject")
Set fldr = fObj.GetFolder(fPath)
For Each fldr In fldr.SubFolders
If fldr.Name = CStr(mn) Then CheckForRecordMonth = True: Exit Function
Next fldr
CheckForRecordMonth = False
End Function
Private Function CheckForRecordDay(ByVal fPath As String, ByVal dy As Variant) As Boolean
Dim fObj As Object, fldr As Object, f As Object
Set fObj = CreateObject("Scripting.FileSystemObject")
Set fldr = fObj.GetFolder(fPath)
For Each fldr In fldr.Files
If fldr.DateCreated < Now() - 6 Then CheckForRecordDay = False: Exit Function
Next fldr
CheckForRecordDay = True
End Function