Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a named sheet at the end of all Excel sheets?

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?

like image 479
Behseini Avatar asked Dec 20 '13 06:12

Behseini


People also ask

How do you autofill sheet names in Excel?

Enter SheetNames into the Name field, enter the following formula into the Refers to field: =REPLACE(GET. WORKBOOK(1),1,FIND("]",GET. WORKBOOK(1)),""), and then select OK. This action will create a named formula that can then be used in conjunction with the INDEX function to produce a list of worksheet names.


2 Answers

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 
like image 194
L42 Avatar answered Nov 16 '22 00:11

L42


Kindly use this one liner:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name" 
like image 43
Amar Avatar answered Nov 16 '22 01:11

Amar