76

I am trying to add an Excel sheet named "Temp" at the end of all existing sheets, but this code is not working:

Private Sub CreateSheet()
    Dim ws As Worksheet
    ws.Name = "Tempo"
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
End Sub

Can you please let me know why?

ZygD
  • 22,092
  • 39
  • 79
  • 102
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • 2
    Because you haven't created `ws` prior to assigning a `.Name`. Don't get confused: instantiate your variable first before attempting to access its properties. – WGS Dec 20 '13 at 06:41

8 Answers8

167

Try this:

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = "Tempo"
End Sub

Or use a With clause to avoid repeatedly calling out your object

Private Sub CreateSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = "Tempo"
    End With
End Sub

Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub
L42
  • 19,427
  • 11
  • 44
  • 68
  • why what's wrong? you are not creating the sheet in the same workbook? – L42 Dec 20 '13 at 06:48
  • 11
    ThisWorkbook is the workbook that hosts the running macro. ActiveWorkbook is the the workbook the user is working (said in plain terms). WorkBooks("somename") addresses a specific open workbook – Massimo Fuccillo Dec 20 '13 at 09:16
  • 1
    Nice, but what happens if sheet already exist, Would it throw an error ? – Ch32k0 Aug 26 '16 at 21:20
  • 1
    @Ch32k0 Yes. If the same name already exist or if you use an invalid name. – L42 Sep 02 '16 at 03:21
  • @L42 Oh, I experimented with this and it actualy does, thanks for the feedback – Ch32k0 Sep 16 '16 at 18:57
42

Kindly use this one liner:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"
Amar
  • 429
  • 4
  • 6
  • 1
    Sorry, but the accepted answer looks better. This one does not explicitly indicate `ThisWorkbook` or `ActiveWorkbook`. Also, the new worksheet object here is not assigned to a variable, while afterwards almost always you will want to use it for putting data into the sheet. – ZygD Feb 21 '19 at 08:50
  • 1
    I think this answer does the trick best. It is not specified that the sheet should be assigned to a variable. He know's it's name obviously since it's specified in the code. – IronWilliamCash Apr 08 '19 at 02:41
7
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(when you add a worksheet, anyway it'll be the active sheet)

Saptarshi
  • 125
  • 2
  • 3
5

Try this:

Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
    On Error GoTo the_dark

    Dim wsSheet As Worksheet
    Dim bFoundWS As Boolean
    bFoundWS = False
    If inNamePrefix <> "" Then
        Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
    End If

    If inBeforeOrAfter = iAfter Then
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
        Else
            Worksheets.Add(After:=wsSheet).Name = inName
        End If
    Else
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(Before:=Worksheets(1)).Name = inName
        Else
            Worksheets.Add(Before:=wsSheet).Name = inName
        End If
    End If

    Set addSheet = findWS(inWB, inName, bFoundWS)         ' just to confirm it exists and gets it handle

    the_light:
    Exit Function
    the_dark:
    MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
    Err.Clear
    GoTo the_light
End Function
JF it
  • 2,403
  • 3
  • 20
  • 30
Mr F
  • 51
  • 1
  • 1
4

Try to use:

Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"

If you want to check whether a sheet with the same name already exists, you can create a function:

Function funcCreateList(argCreateList)
    For Each Worksheet In ThisWorkbook.Worksheets
        If argCreateList = Worksheet.Name Then
            Exit Function ' if found - exit function
        End If
    Next Worksheet
    Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function

When the function is created, you can call it from your main Sub, e.g.:

Sub main

    funcCreateList "MySheet"

Exit Sub
Ivan Tokarev
  • 101
  • 6
4


Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

thanks,

Developer
  • 761
  • 7
  • 12
3

This will give you the option to:

  1. Overwrite or Preserve a tab that has the same name.
  2. Place the sheet at End of all tabs or Next to the current tab.
  3. Select your New sheet or the Active one.

Call CreateWorksheet("New", False, False, False)


Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
  activeSheetNumber = Sheets(ActiveSheet.Name).Index

  If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
    If (preserveOldSheet) Then
      MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
      Exit Sub
    End If
      Application.DisplayAlerts = False
      Worksheets(sheetName).Delete
    End If

    If (isLastSheet) Then
      Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
    Else 'Place sheet after the active sheet.
      Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
    End If

    If (selectActiveSheet) Then
      Sheets(activeSheetNumber).Activate
    End If

End Sub
moberme
  • 669
  • 7
  • 13
-2

This is a quick and simple add of a named tab to the current worksheet:

Sheets.Add.Name = "Tempo"
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Jan
  • 421
  • 3
  • 13