VBA copy template sheet to new monthly workbook with daily sheets tabname and header A2:J2 named as "dd mm yyyy" + autosave filename predefined

SimpleUser

New Member
Joined
Jun 20, 2016
Messages
9
Hi. I found this on contextures and it creates monthly workbook with separate daily blank sheets and date as the tabname. How do I change it to copy a template sheet instead of creating blank sheets? Also, to add the code to change merged cell of A2:J2 to the date created each day as "DD MMM YYYY"?

I tried replacing the part where it creates the sheets to as below but I got some sub error
VBA Code:
Sheets("Template").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = Format(DateSerial(yr, m, mDay), "dd mmm yyyy")
ActiveSheet.Range("A2:J2").Value = Format(DateSerial(yr, m, mDay), "dd mmm yyyy")

The working file I got from contextures.
VBA Code:
Option Explicit
' Downloaded from www.contextures.com
'---------------------------------------------------------------------------------------
' Procedure : CreateBooksandSheets
' Author    : Roger Govier, Technology 4 U
' Date      : 13/01/2008 , modified 30 Nov 2008
' Purpose   :
' Creates 12 workbooks named Jan YYYY.... Dec YYYY
' In each workbook, creates the number of sheets for each day in the month
' and names them Jan 01, Jan 02 etc.
' Deletes the standard Sheet1 to Sheet3 created as part of a normal workbook.
' Amended Nov 29 08
' amended from deleting the array of Sheet1, Sheet2, Sheet3  after it was pointed
' out by Mike Fogleman, there is no guarantee that the user allows new
' workbooks to be created with 3 sheets. If there are less than 3, the previous version
' errored out. Also added Mike's suggestion for creating ordinal numbers.
' Amended Nov 28 2022 - by Debra Dalgleish
' in macro, changed file extension to xlsx
' changed workbook naming to yyyy_mm
' use eomonth function to get last day in month
'---------------------------------------------------------------------------------------

Sub CreateBooksandSheets()
    'Dim month As String, year As String
    Dim yr As Integer, m As Integer
    Dim folder As String, filename As String
    Dim mName As String, tabname As String
    Dim mDay As Integer, mEnd As Integer
    Dim ordinals As Boolean
    Dim ws As Worksheet
    Dim ext As String
    Dim wbT As Workbook
    
   On Error GoTo CreateBooksandSheets_Error
    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
    End With
        
    folder = ThisWorkbook.Path
    ext = ".xlsx"
    
askyear:
    yr = Format(Now(), "yyyy")
    yr = InputBox("Enter the Year number required" _
                & vbCrLf & "in the format of  YYYY e.g. " & yr + 1 _
                & vbCrLf & "" _
                & vbCrLf & "This will determine the correct" _
                & vbCrLf & "number of days for February." _
                , "Enter Year Number", yr + 1)
 
    If Val(yr) < 1999 And Val(yr) > 2100 Then
        GoTo askyear
    End If
    
     ' ask if the user want to use ordinals for the day numbers 1st, 2nd, 3rd etc.
        ' added after suggestion by Mike Fogleman
        Select Case MsgBox("Do you want to use Ordinals for the number format" _
            & vbCrLf & "e.g Jan 1st, Jan 2nd etc." _
            & vbCrLf & "Answer YES if required, or NO to leave as Jan 01, Jan 02" _
            , vbYesNo Or vbQuestion Or vbDefaultButton1, "Use Ordinals?")

        Case vbYes
            ordinals = True
        Case vbNo
            ordinals = False
        End Select

    For m = 1 To 12    ' i.e. for each of the 12 months of the year

        mName = MonthName(m, True)  'select monthname in short Form
        filename = "Keypress Access Log " & Format(m, "00") & " " & Format(mName, "MMM") & " " & yr 'See Chye's edit to save filename as eg. Keypress Access Log 03 Mar YYYY
        ' test if file for Month already exists, If so ask user whether they want to overwrite the file
        ' uses the IsFile function below this module

        If IsFile(filename & ext) Then
            Select Case MsgBox("The file   " & filename & ext _
                  & vbCrLf & "already exists." _
                  & vbCrLf & "Do you want to Overwrite this file?" _
                  & vbCrLf & "Cancel will stop the macro from continuing" _
                  , vbYesNoCancel Or vbExclamation Or vbDefaultButton2, _
                  "File Alreday Exists")

            Case vbNo
                GoTo nextmonth

            Case vbCancel
                GoTo exitsub
                
            Case vbYes

            End Select
        End If
    
        Workbooks.Add  'create new Workbook and save as Month name

        On Error Resume Next      ' user has said Ok to overwrite to ignore warning
        ActiveWorkbook.SaveAs filename:=folder & "\" & filename & ext
        
        On Error GoTo CreateBooksandSheets_Error    ' set error point back
        'add new sheet after existing sheets in workbook and name it same as month

        Worksheets.Add(After:=Sheets(Sheets.Count)).Name = mName

        'delete any other sheets in the newly opened workbook
       For Each ws In ActiveWorkbook.Worksheets
            If ws.Name <> mName Then
                ws.Delete
            End If
        Next
            
        mEnd = Day(Application.WorksheetFunction _
            .EoMonth(DateSerial(yr, m, 1), 0))
        For mDay = 1 To mEnd
            
            If ordinals <> True Then
                'Sheets("Template").Copy After:=Sheets(Sheets.Count)
                'ActiveSheet.Name = Format(DateSerial(yr, m, mDay), "dd mmm yyyy")
                'ActiveSheet.Range("A2:J2").Value = Format(DateSerial(yr, m, mDay), "dd mmm yyyy")
                Worksheets.Add(After:=Sheets(Sheets.Count)). _
                        Name = Format(DateSerial(yr, m, mDay), "dd mmm yyyy")
                        'if you don't want the month name included, just the day number, then
                        'change the format above to just "dd" instead of "mmm dd"

            Else
                Select Case mDay
                Case 1, 21, 31
                    tabname = mDay & "st"
                Case 2, 22
                    tabname = mDay & "nd"
                Case 3, 23
                    tabname = mDay & "rd"
                Case Else
                    tabname = mDay & "th"
                End Select
                ' if you don't want the Month in the sheet name, just the day number
                ' then rem out the next line
                tabname = tabname & " " & mName & " " & Format(DateSerial(yr, m, mDay), "yyyy")
                Worksheets.Add(After:=Sheets(Sheets.Count)). _
                        Name = tabname
            End If
        Next mDay

        ' now delete the first sheet created with just the month name
        Sheets(mName).Delete
        
        ' save the workbook and close
        ActiveWorkbook.Close Savechanges:=True

        ' step up month number to next month and repeat procedure
        ' this is the point we jump to if file exists
        '   and user says NO to overwrite.
        
nextmonth:
    Next m
    Call MsgBox("All monthly files have been created" _
                & vbCrLf & "in folder " & folder _
                , vbInformation Or vbDefaultButton1, _
                "Macro completed")
    
    GoTo exitsub

CreateBooksandSheets_Error:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ")" _
      & vbCrLf _
      & " in procedure CreateBooksandSheets of Module Module1"
    Application.DisplayAlerts = True

exitsub:
With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
    End With
End Sub


Function IsFile(s As String) As Boolean
'tests whether a file exists. Returns True if it does or False
    Dim fs
    Set fs = CreateObject("Scripting.FileSystemObject")
    IsFile = fs.FileExists(s)
End Function


' Alternative method of creating ordinal number.
' This function was posted by Excel MVP Rick Rothstein in the Newsgroups on 01 Dec 2008

Function Ordinal(Number As Long) As String
  Ordinal = Number & Mid$("thstndrdthththththth", 1 - 2 * _
            ((Number) Mod 10) * (Abs((Number) Mod 100 - 12) > 1), 2)
End Function

The template I'm trying to duplicate with tabname as date and header <Date> in the 2nd merged cell. Much help is appreciated.
excelcreateyrmthworkbks.xlsm
ABCDEFGHIJ
1Keypress Access Log
2<Date>
3S/NoRequesterCompanySR No.KeyOwnerPurposeTime OutTime InEscort by
4
5
6
7
8
9Check by:Verified by:
10
Template
 

Excel Facts

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.
Place this macro in the workbook containing the Template sheet and save the workbook as a macro-enabled file. The monthly workbooks will be saved in the same folder as the Template workbook.
VBA Code:
Sub CreateMonthlyFiles()
    Application.ScreenUpdating = False
    Dim x As Long, y As Long, DaysInMonth As Long, year As String, srcWS As Worksheet
    Set srcWS = ThisWorkbook.Sheets("Template")
    year = InputBox("Please enter the desired year.")
    If year = "" Then Exit Sub
    For x = 1 To 12
        DaysInMonth = DateSerial(year, x + 1, 1) - DateSerial(year, x, 1)
        srcWS.Copy
        For y = 1 To DaysInMonth
            Sheets(1).Copy after:=Sheets(Sheets.Count)
            With ActiveSheet
                .Name = DateSerial(year, x, y)
                .Range("A2") = DateSerial(year, x, y)
            End With
        Next y
        Application.DisplayAlerts = False
        Sheets(1).Delete
        Application.DisplayAlerts = True
        With ActiveWorkbook
            .SaveAs ThisWorkbook.Path & Application.PathSeparator & year & "_" & MonthName(x) & ".xlsx", FileFormat:=51
            .Close False
        End With
    Next x
    Application.ScreenUpdating = True
End Sub
 
Upvote 0
Solution
Place this macro in the workbook containing the Template sheet and save the workbook as a macro-enabled file. The monthly workbooks will be saved in the same folder as the Template workbook.
VBA Code:
Sub CreateMonthlyFiles()
    Application.ScreenUpdating = False
    Dim x As Long, y As Long, DaysInMonth As Long, year As String, srcWS As Worksheet
    Set srcWS = ThisWorkbook.Sheets("Template")
    year = InputBox("Please enter the desired year.")
    If year = "" Then Exit Sub
    For x = 1 To 12
        DaysInMonth = DateSerial(year, x + 1, 1) - DateSerial(year, x, 1)
        srcWS.Copy
        For y = 1 To DaysInMonth
            Sheets(1).Copy after:=Sheets(Sheets.Count)
            With ActiveSheet
                .Name = DateSerial(year, x, y)
                .Range("A2") = DateSerial(year, x, y)
            End With
        Next y
        Application.DisplayAlerts = False
        Sheets(1).Delete
        Application.DisplayAlerts = True
        With ActiveWorkbook
            .SaveAs ThisWorkbook.Path & Application.PathSeparator & year & "_" & MonthName(x) & ".xlsx", FileFormat:=51
            .Close False
        End With
    Next x
    Application.ScreenUpdating = True
End Sub

I place the code on the "Template" sheet, ran the code and got run time error 1004. Please help.
 

Attachments

  • Screenshot 2023-03-05 145001.png
    Screenshot 2023-03-05 145001.png
    54.1 KB · Views: 11
Upvote 0
Place this macro in the workbook containing the Template sheet and save the workbook as a macro-enabled file. The monthly workbooks will be saved in the same folder as the Template workbook.
VBA Code:
Sub CreateMonthlyFiles()
    Application.ScreenUpdating = False
    Dim x As Long, y As Long, DaysInMonth As Long, year As String, srcWS As Worksheet
    Set srcWS = ThisWorkbook.Sheets("Template")
    year = InputBox("Please enter the desired year.")
    If year = "" Then Exit Sub
    For x = 1 To 12
        DaysInMonth = DateSerial(year, x + 1, 1) - DateSerial(year, x, 1)
        srcWS.Copy
        For y = 1 To DaysInMonth
            Sheets(1).Copy after:=Sheets(Sheets.Count)
            With ActiveSheet
                .Name = DateSerial(year, x, y)
                .Range("A2") = DateSerial(year, x, y)
            End With
        Next y
        Application.DisplayAlerts = False
        Sheets(1).Delete
        Application.DisplayAlerts = True
        With ActiveWorkbook
            .SaveAs ThisWorkbook.Path & Application.PathSeparator & year & "_" & MonthName(x) & ".xlsx", FileFormat:=51
            .Close False
        End With
    Next x
    Application.ScreenUpdating = True
End Sub

I managed to get it working as intended after some tweaking by adding some of the code from the initial working file. Here's what I added and tweaked.

VBA Code:
Sub CreateMonthlyFiles()
    Application.ScreenUpdating = False
    Dim Mth As Long, dy As Long, DaysInMonth As Long, yr As String, srcWS As Worksheet
    Set srcWS = ThisWorkbook.Sheets("Template") 'Name of worksheet that will be compiled to new workbook
    
askyear:
    yr = InputBox("Enter the Year number required" _
                & vbCrLf & "in the format of  YYYY e.g. " & "2023" _
                & vbCrLf & "" _
                , "Enter Year Number")
    If yr = "" Or Val(yr) = 0 Then Exit Sub
    If Val(yr) < 1999 Or Val(yr) > 2100 Then
        GoTo askyear
    End If
    For Mth = 1 To 12
        DaysInMonth = DateSerial(yr, Mth + 1, 1) - DateSerial(yr, Mth, 1)
        srcWS.Copy
        For dy = 1 To DaysInMonth
            Sheets(1).Copy After:=Sheets(Sheets.Count)
            With ActiveSheet
                .Name = Format(DateSerial(yr, Mth, dy), "dd MMMM yyyy")
                .Range("A2:J2") = Format(DateSerial(yr, Mth, dy), "dd MMMM yyyy")
            End With
        Next dy
        Application.DisplayAlerts = False
        Sheets(1).Delete
        Application.DisplayAlerts = True
        With ActiveWorkbook
            .SaveAs ThisWorkbook.Path & Application.PathSeparator & "Keypress Access Log " & Format(Mth, "00") & " " & MonthName(Mth) & " " & yr & ".xlsx", FileFormat:=51
            .Close False
        End With
    Next Mth
    Application.ScreenUpdating = True
End Sub

Thanks Mumps for the help. You have made the code so much simpler and straightforward.
 
Upvote 0

Forum statistics

Threads
1,223,943
Messages
6,175,546
Members
452,652
Latest member
eduedu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top