Create new worksheets programmatically based on values in a cell range [VBA]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may have multiple columns if you like.
This macro allows you to create new worksheets very quickly.
Table of Contents
1. Create new worksheets programmatically based on values in a cell range
1.1 How this macro works
The animated image above shows how this macro works.
- Press Alt + F8 to open the Macro dialog box.
- Select macro CreateSheets.
- Press with mouse on "Run" button.
- An input box appears asking for a cell range.
- Select a cell range and press with left mouse button on the "OK" button.
- Worksheets are now added automatically to the workbook and named correspondingly after the values in the cell range.
1.2 VBA macro
'Name macro Sub CreateSheets() 'Dimension variables and declare data types Dim rng As Range Dim cell As Range 'Enable error handling On Error GoTo Errorhandling 'Show inputbox to user and prompt for a cell range Set rng = Application.InputBox(Prompt:="Select cell range:", _ Title:="Create sheets", _ Default:=Selection.Address, Type:=8) 'Iterate through cells in selected cell range For Each cell In rng 'Check if cell is not empty If cell <> "" Then 'Insert worksheet and name the worksheet based on cell value Sheets.Add.Name = cell End If 'Continue with next cell in cell range Next cell 'Go here if an error occurs Errorhandling: 'Stop macro End Sub
1.3 Where to put the code
- Copy above VBA code.
- Press Alt + F11 to open the Visual Basic Editor.
- Press with mouse on your workbook in the Project Explorer.
- Press with mouse on "Insert" on the menu.
- Press with mouse on "Module".
- Paste VBA code to code window, see image above.
1.4 Explaining code
Creating procedures in excel is easy. Open the Visual Basic Editor using one of these instructions:
- Press Alt+F11
- Go to tab Developer and press with left mouse button on Visual basic "button"
You create macro procedures in a module. First create a module. Press with right mouse button on on your workbook in the project explorer. Press with left mouse button on Insert | Module.
Sub CreateSheets()
Type: Sub CreateSheets()Â in the module. CreateSheets() is the name of the macro.
Dim rng As Range
Dim cell As RangeÂ
These lines declare rng and cell as range objects.  A range object can contain a single cell, multiple cells, a column or a row. Read more about declaring variables.
On Error Goto Errorhandling
If the user selects something else than a cell range like a chart, this line makes the procedure go to Errorhandling.
Set rng = Application.InputBox(Prompt:="Select cell range:", _
Title:="Create sheets", _
Default:=Selection.Address, Type:=8)
The inputbox asks the user for a cell range. The cell range is stored in the range object rng.
For Each cell In rng
This stores each cell value from the range object rng to the cell object, one by one.
If cell <> "" Then
Checks if the cell variable is NOT empty. If the cell variable is empty the procedure goes to "End If" line. We can't create a sheet with no name.
Sheets.Add.Name = cell
Creates a new sheet named with the value stored in the cell variable.
End If
The end of the If statement.
Next cell
Go back to the "For each" statement and store a new single cell in the cell object.
Errorhandling:
The procedure goes to this line if a line returns an error.
End Sub
All procedures must end with this line.
1.5 Excel file
Recommended reading
List all open workbooks and corresponding sheets (vba)
2. Create new worksheets programmatically based on a comma-delimited list
The image above shows a comma delimited list in cell B2, the macro below in section 2.1 lets you select a cell containing a comma delimiting list.
It splits the string based on the comma into an array of values. The values are then used to insert new worksheets with names based on those array values.
2.1 VBA code
Sub CreateSheetsFromList() Dim rng As Range Dim cell As Range Dim Arr As Variant On Error GoTo Errorhandling Set rng = Application.InputBox(Prompt:="Select cell:", _ Title:="Create sheets", _ Default:=Selection.Address, Type:=8) Arr = Split(rng.Value, ", ") For Each Value In Arr If Value <> "" Then Sheets.Add.Name = Value End If Next Value Errorhandling: End Sub
2.2 Excel file
3. Create new worksheets using an Input box
The following macro displays an input box allowing the Excel user to type a worksheet name, the worksheet is created when the "OK" button is pressed.
The macro stops if nothing is typed or the user presses the "Cancel" button. It shows a new input box each time a new worksheet is created.
3.1 VBA code
Sub CreateSheetsFromDialogBox() Dim str As String Dim cell As Range Dim Arr As Variant On Error GoTo Errorhandling Do str = Application.InputBox(Prompt:="Type worksheet name:", _ Title:="Create sheets", Type:=3) If str = "" Or str = "False" Then GoTo Errorhandling: Else Sheets.Add.Name = str End If Loop Until str = "False" Errorhandling: End Sub
3.2 Excel file
4. Copy the worksheet template and rename
This example demonstrates an Event macro that copies a worksheet based on a value in cell E2 and renames it to a cell value in column B.
4.1 VBA event code
'Event code that runs if a cell value is changed Private Sub Worksheet_Change(ByVal Target As Range) 'Check if the cell value is in column B If Not Intersect(Target, Range("B:B")) Is Nothing Then 'Copy worksheet based on value in cell E2 in worksheet Sheet1 and put it last Sheets(Worksheets("Sheet1").Range("E2").Value).Copy , Sheets(Sheets.Count) 'Rename worksheet to the value you entered. ActiveSheet.Name = Target.Value End If 'Go back to worksheet Sheet1 Worksheets("Sheet1").Activate End Sub
4.2 Where to put the event code?
- Press Alt + F11 to open the Visual Basic Editor.
- Double press with left mouse button on with the left mouse button on the worksheet name where you want to put the event code, in the worksheet Explorer shown in the image above.
- Paste event code to the code window, also shown in the image above.
- Return to Excel.
4.3 How to run macro?
The event code runs whenever a new value is entered in column B. For example, type Trend in cell B5, then press Enter.
The macro automatically copies the worksheet "Template" given in cell E2 and renames it to Trend. That is all.
Macro category
This article demonstrates how to add or remove a value in a regular drop down list based on a list […]
In this tutorial, I am going to show you how to add values to a drop down list programmatically in […]
This article demonstrates how to place values automatically to a table based on two conditions using a short macro. Cell […]
This tutorial shows you how to add a record to a particular worksheet based on a condition, the image above […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]
In this article I will demonstrate how to quickly change chart data range utilizing a combobox (drop-down list). The above […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don't know the […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
I will in this article demonstrate a macro that counts how many times a specific text string is found in […]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]
Question: hi all, thanks for the great formula/array formula. it works great. lately, i noticed that the array formula will […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
Save links to your favorite macros in a personal tab on the ribbon for easy access and become more productive. […]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]
In this article, I am going to demonstrate a simple workbook where you can create or delete projects and add […]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet. Jinesh asks: […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
In this tutorial, I am going to demonstrate how to filter an Excel define Table through a VBA macro. How it […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This post Find the longest/smallest consecutive sequence of a value has a few really big array formulas. Today I would like to […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This article demonstrates event code combined with Conditional Formatting that highlights overlapping date ranges based on the selected date range. […]
This post describes how to add a new custom-built item to the shortcut menu in Excel, when you press with right […]
The Quick Access Toolbar is located at the very top of your Excel window, I highly recommend that you place your […]
Rahul asks: I want to know how to create a vlookup sheet, and when we enter a name in a […]
This article demonstrates a formula and a VBA macro that returns every n-th row from a given cell range. The […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
This article describes how to create an interactive chart, the user may press with left mouse button on a button […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates how to automatically create log entries when a workbook opens or closes using event code. Column A […]
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]
Macros and custom functions are great, they can automate many tedious tasks. To have them available whenever you need them, […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]
This article demonstrates a User Defined Function (UDF) that multiplies numbers in each row with the remaining rows in a […]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
This article explains how to set up a workbook so a macro is run every time you open the workbook. […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
This article demonstrates a macro that allows you to rearrange and distribute concatenated values across multiple rows in order to […]
In this post I am going to rearrange values from a list into unique columns. Before: After: The code Get […]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two […]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article explains how to hide a specific image in Excel using a shape as a button. If the user […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]
This blog post describes how to insert qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
Excel categories
15 Responses to “Create new worksheets programmatically based on values in a cell range [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Hi Oscar,
Thank you so much for this Macro. A simple idea but was lot more useful since it allowed the user to create only those file that are required from the unique list.
Hi- this is not working at all for me. It just creates one sheet.
I can't figure out what is wrong -
Hi!
is the length of the name more than 31 characters? That was trouble for me anyways. I used "length" to take only 31 characters since my names are still unique with only 31 characters. Then using the macro works :)
//Michael
Hi there,
i was wondering if there was any way of creating the sheets to the right side of the activesheet(sheet1).
Right now it creates the sheets to the left of it.
One question of my own though:
It creates the variables in the wrong order. Line 2 will be the last sheet created (in my case sheet 50). It still works but any tips on how to reverse it?
//Michael
@Smriti @Leissner
To insert each new sheet to the end (right), instead of previous to the working tab (left), change this line in the code:
Sheets.Add.Name = cell
to this:
Sheets.Add(After:=Sheets(Sheets.Count)).Name = cell
That worked even better than expected - I had several batches and your new code made the new batches each appear as far right as possible.
Wow, you just saved me an insane amount of boring work (70 tabs to create). I used another snippet of code to alphabetize them too and then used Michael Reese's suggestion and it worked beautifully with your code. Thank you!
how to creat sheet according to month
Hi Please what if I have more than 1 row containing the same values and I want it not only to create a new row based on the cell value, but also copy the contents on the row that contains identical value into same sheet?
Hi Oscar,
I think this is a great bit of code, but my issue is that I want the tabs on my excel file to be dates that look like this: 9-1-2021, 9-2-2021,... I've figured out that this code doesn't seem to like those dashes (it only creates one blank sheet when I have the dates set up like this in the list). If I change the dates to this format 0901, 0902,... then it runs fine. Any way I can change the code to get my prefered date format?
Debra
Excelente el codigo para crear las hojas a partir de una lista. LA consulta es se puede crear la hoja con u contenido, por ejemplo una ficha para rellenar?
I get an error message saying "Can't execute code in break mode"
It shows the line "If cell <> ""Then" in red.
Do you know what is wrong here?
Hello, this was almost exactly what i was looking for. I had a question on if it was possible to not just generate the new sheet from typing in a cell and name the sheet after the cell but to have the new sheet be a copy on a current sheet that is kind of like a template for a form?
Sami Jo,
great question!
I have added another section to this post:
Copy worksheet template and rename