Click here to Skip to main content
15,885,996 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a new project for clinic reservation in excel and in this project. I require a button to click to create a new sheet with a new date, which is one day more than the date of the previous. I found a code in the internet which create a new sheet with my template but it create the sheet with today date, but what I need is to create sheet with one day more then the last sheet created or the active sheet. Can any one please help?



the code i found is :

What I have tried:

VB
Sub Insert_Sheet_Template()
    Dim sh As Worksheet
    Dim shName As String

    'name of the sheet template
    shName = "template.xltm"

    'Insert sheet template
    With ThisWorkbook
        Set sh = Sheets.Add(Type:=Application.TemplatesPath & shName, _
                            after:=.Sheets(.Sheets.Count))
    End With

    'Give the sheet a name, today's date in this example
    On Error Resume Next
    sh.Name = Format(Date, "yyyy-mmm-dd")
    If Err.Number > 0 Then
        MsgBox "Change the name of Sheet : " & sh.Name & " manually"
        Err.Clear
    End If
    On Error GoTo 0
End Sub
Posted
Updated 25-Jul-18 4:13am
v2

1 solution

Try this function
VB
Private Function FindNextSheetDate() As String
'Steps through the sheets in ThisWorkbook and determines which (if any) are a date
'determines the latest of those dates and adds 1 day 
'returns that date as a string in yyyy-mmm-dd format
'If no sheets are found, returns today's date
'Error handling is assumed to be handled by the calling function

    Dim dt As Date
    Dim maxdt As Date
    maxdt = CDate("1900-Jan-01")
    
    Dim sht As Variant
    For Each sht In ThisWorkbook.Sheets
        If IsDate(sht.Name) Then
            dt = CDate(sht.Name)
            If dt > maxdt Then
                maxdt = dt
            End If
        End If
    Next

    If maxdt = CDate("1900-Jan-01") Then
        'Set maxdt to yesterday as there is a DateAdd of one day in the return value
        maxdt = DateAdd("d", -1, Date)
    End If

    FindNextSheetDate = Format$(DateAdd("d", 1, maxdt), "yyyy-mmm-dd")
    
End Function
Used like
VB
sh.Name = FindNextSheetDate()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900