ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Excel VBA - Guide To Creating A New Sheet Everyday Automatically

Updated on October 14, 2016

Quick Explanation

When excel is opened, VBA can start immediately helping you to do tasks automatically. Once of the most useful I have found is to create a new sheet everyday for me to work from.

This simple, yet effective bit of code will create a new sheet, name the sheet as Todays date and place it at the end of the sheet tab. There's also a Bonus section at the end for generating a new sheet based on a template, follow the normal steps first and then read the Bonus section.

Step 1 - Accessing VBA

VBA can be accessed in one of two ways:

  1. Simply press ALT + F11 when Excel is open on a new workbook
  2. Head to the Options and select "View Developer Tab" then click Visual Basic (2007 Onwards)

When the editor opens, you'll be presented with a grey window with a project manager down the left hand side.

Double click on "ThisWorkbook" - This is where we'll be writing our code for this guide. When double clicked, you'll be presented with a blank document on the right hand side of the window

Step 2 - Write VBA For Detecting The Workbook Opening

In the blank space on the right hand side, write the following code:

Private Sub Workbook_Open()

End Sub

This now tells Excel that when the workbook is opened, everything between these lines needs to be executed.

Step 3 - Adding A New Sheet

The code for adding a new sheet is really simple, as simple as "Sheets.Add". But the problem with using the bog standard, easy way is that the sheet will be added with the name "Sheet X" and will appear as the first sheet in the workbook.

We want to add a sheet, name it as today's date and place it at the end of the sheet tab at the bottom of the Excel window.

Write the following code between the two lines written in Step 1

Sheets.Add(After:=Sheets(Sheets.Count)).Name = TodaysDate

The "Sheets.Add" is still the part of the code that is adding the sheet, but we are giving it some extra parameters in order to tailor how it works to our needs. After the brackets open, the "After:=" tells VBA to expect a parameter to tell it where to place the sheet. The "Sheets(Sheets.Count)" is telling the "After" command that it should go After the sheet with the index number that is the same as the amount of sheets in the workbook, the last sheet.

The ".Name" on the end allows us to specify a name during the creation of the workbook. "TodaysDate" is a variable tag, which we haven't defined yet, we'll do that now

Step 4 - Getting Today's Date

If we're going to name the new worksheet as today's date, we need to know what the date is.

Underneath the opening line you wrote in step 1 ("Private Sub Workbook_Open()"), write the following code:

'Get Todays Date
Dim TodaysDate As String
TodaysDate = Format(Now(), "dd-mm-yyyy")

The "Dim TodaysDate As String" sets the variable up as an empty string

The "TodaysDate = Format(Now(), "dd-mm-yyyy")" is getting the date and time as it is right now, and converting it in to the format of Day, Month, Year. The result is then placed in the variable "TodaysDate"

This variable will then be used in the previous step to name the worksheet as the current date

Step 5 - Checking The Worksheet Doesn't Already Exist

Before we move on, let's quickly check that you're code is up to date, it should look like this at the moment:

Private Sub Workbook_Open()

'Get Todays Date
Dim TodaysDate As String
TodaysDate = Format(Now(), "dd-mm-yyyy")
	
Sheets.Add(After:=Sheets(Sheets.Count)).Name = TodaysDate

End Sub

We might open the workbook more than once during the same day, if so, we want to stop the workbook from trying to create another sheet for today (it will fail and throw an annoying error message).

Place the following code between your Date code and your Add Sheet code

'Check Todays Sheet Doesn't Already Exist
Dim SheetExists As Boolean
For sheetnames = Worksheets.Count To 1 Step -1
    If Worksheets(sheetnames).Name = TodaysDate Then
        SheetExists = True
        Exit For
    End If
Next

The "Dim SheetExists As Boolean" creates a new variable that is either true or false (false by default).

The "For sheetnames = Worksheets.Count To 1 Step -1" sets up a variable called "sheetnames" and assigns it a value of the number of sheets set by the "Worksheets.Count" command. The "To 1 Step - 1" tells the code to count backwards from "sheetnames" by 1 until all the value of "sheetnames" is equal to 1.

The code between the "For" and "Next" is then executed on every iteration through the number of sheets. If the sheet that is being checked is found to have Todays Date as it's name, the "SheetExists" variable is set to True and the checks stop. If no sheet is found then the "SheetExists" variable remains False

Now all that is left to do is to ensure that if the sheet does exist already, not to execute the command to create a new sheet.

Wrap the Add command in the following so that it looks like this:

If SheetExists = False Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = TodaysDate
End If

Summary

And that's it, you now have a code that runs every time the workbook is opened, that creates a new sheet, names it today's date, places it at the end of the tab bar and checks if one is already created. Simply click the save button in excel and save as a "Macro Enabled Workbook", close everything, open it up again and see it create your first auto-generated sheet.

(You can also click the Play button in the VBA editor when the cursor is between the first and last line of the code to run it instantly)

Your complete code should look like the following:

Private Sub Workbook_Open()
 
'Get Todays Date
Dim TodaysDate As String
TodaysDate = Format(Now(), "dd-mm-yyyy")

'Check Todays Sheet Doesn't Already Exist
Dim SheetExists As Boolean
For sheetnames = Worksheets.Count To 1 Step -1
    If Worksheets(sheetnames).Name = TodaysDate Then
        SheetExists = True
        Exit For
    End If
Next
     
If SheetExists = False Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = TodaysDate
End If
 
End Sub

Bonus - Adding A New Sheet From A Template

Just incase you want a sheet with a template generated everyday opposed to a blank sheet, simply change the last section of the code to the following:

If SheetExists = False Then
Worksheets("Sheet1").Copy After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = TodaysDate
End If

This will copy the format in "Sheet1" (Or whatever your template sheet is called) to a new sheet.

TIP: After making your Template sheet, right click it in the sheet tab at the bottom of the page and set it to "Hidden" by clicking "Hide". The VBA code will still be able to read it, and you wont have a template tab just sat there.

Note: If the template sheet is changed, the changes will only be applied to new sheets that are generated after the change.

Following the guide above, did you get this working?

See results

How Did It Go?

If you couldn't get this working, pop a comment below explaining where you got stuck and I'll help where I can or change this hub to reflect where people are having issues

Comments

    0 of 8192 characters used
    Post Comment

    • LiamBee profile imageAUTHOR

      Liam 

      4 weeks ago from UK

      @Rae glad it worked for you

    • profile image

      Rae 

      6 weeks ago

      This worked perfectly for Excel for Mac 2016. Thank you!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)