
Tips.Net > ExcelTips Home > Macros > Creating Worksheets with a Macro
Summary: Macros are often used to process worksheets. In doing your processing, you may actually want to add a new worksheet from within the macro. This tip explains how to accomplish this task. (This tip works with Microsoft Excel 97, Excel 2000, Excel 2002, and Excel 2003.)
Excel lets you create new worksheets in a number of different ways. What if you want to create a new worksheet and name it all in one step? The easiest way to do this is with a macro. The following is an example of a macro that will ask for a name, and then create a worksheet and give that worksheet the name provided.
Sub AddNameNewSheet1()
Dim Newname As String
Newname = InputBox("Name for new worksheet?")
If Newname <> "" Then
Sheets.Add Type:=xlWorksheet
ActiveSheet.Name = Newname
End If
End Sub
This macro works fine, as long as the user enters a worksheet name that is "legal" by Excel standards. If the new name is not acceptable to Excel, the worksheet is still added, but it is not renamed as expected.
A more robust macro would anticipate possible errors in naming a worksheet. The following example code will add the worksheet, but keep asking for a worksheet name if an incorrect one is supplied.
Sub AddNameNewSheet2()
'Remember where we started
'Not needed if you don't want to return to where you started but want
'to stay on the New Sheet
Dim CurrentSheetName As String
CurrentSheetName = ActiveSheet.Name
'Add New Sheet
Sheets.Add
'Make sure the name is valid
On Error Resume Next
'Get the new name
ActiveSheet.Name = InputBox("Name for new worksheet?")
'Keep asking for name if name is invalid
Do Until Err.Number = 0
Err.Clear
ActiveSheet.Name = InputBox("Try Again!" _
& vbCrLf & "Invalid Name or Name Already Exists" _
& vbCrLf & "Please name the New Sheet")
Loop
On Error GoTo 0
'Go back to where you started
'Not needed if you don't want to return to where you started but want
'to stay on the New Sheet
Sheets(CurrentSheetName).Select
End Sub
Tip #2022 applies to Microsoft Excel versions: 97 2000 2002 2003
Got the Time? If you work with either times or dates in Excel, you really need ExcelTips: Times and Dates. Everything you need to know about slicing, dicing, and generally working with times and dates.
Thousands of ExcelTips, available for immediate download. Have all the Microsoft Excel info you need, right at your fingertips. (more information...)
Ask an Excel Question
Make a Comment
ExcelTips FAQ
ExcelTips Premium
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Pet Tips
Word2007 Tips
WordTips
Advertise on the
ExcelTips Site