Google ExcelAutomate.com: Creating Worksheets with a Macro

Creating Worksheets with a Macro

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()
    Dim CurrentSheetName As String

'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

    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

This tip applies to Excel 2007 and 2010 only. 

No comments:

Post a Comment