Excel add sheet at end

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's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

asked Dec 20, 2013 at 6:33

Behseini's user avatar

1

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

answered Dec 20, 2013 at 6:39

L42's user avatar

L42L42

19.3k11 gold badges43 silver badges68 bronze badges

5

Kindly use this one liner:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"

answered Jan 3, 2016 at 5:27

Amar's user avatar

AmarAmar

4294 silver badges6 bronze badges

2

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

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

answered Sep 14, 2015 at 7:56

Saptarshi's user avatar

SaptarshiSaptarshi

1252 silver badges3 bronze badges

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's user avatar

JF it

2,4033 gold badges20 silver badges30 bronze badges

answered Oct 7, 2014 at 12:44

Mr F's user avatar

Mr FMr F

511 silver badge1 bronze badge

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

answered Mar 23, 2016 at 10:14

Ivan Tokarev's user avatar

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,

answered Nov 15, 2016 at 19:04

Developer's user avatar

DeveloperDeveloper

7417 silver badges12 bronze badges

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

answered Oct 17, 2017 at 22:19

moberme's user avatar

mobermemoberme

6597 silver badges13 bronze badges

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

Sheets.Add.Name = "Tempo"

rink.attendant.6's user avatar

answered Oct 22, 2015 at 19:04

Jan's user avatar

JanJan

4113 silver badges9 bronze badges

Skip to content

I can think of five ways to add a new worksheet to a workbook. There may be more, but I can only think of five.

  1. Alt + i + w – this is the way I do it now. I’m trying to get away from the 2003 keyboard shortcuts, but this one remains.
  2. Alt + h + i + s – this is what I should be using because it’s on the Ribbon, but it’s also one extra key.
  3. Click the Insert Worksheet “tab” to the right of all the real sheets.
  4. Use the Shift + F11 keyboard shortcut for the Insert Worksheet “tab” that inexplicably behaves differently than clicking the tab.
  5. Right clicking on a sheet tab and choosing Insert… and going through the dialog box.

Only one of these five methods inserts the worksheet to the right of the active sheet, kind of. #3, the mouse only one, inserts a worksheet at the end of all sheets. All the other methods, including Shift + F11, insert a worksheet to the left of the active worksheet. I’m not much of a clicky guy as you know, preferring the keyboard. But sometimes I want the new worksheet to be at the end. So what’s a guy to do? Acquiesce and reach for the mouse? I don’t think so.

I have an add-in called UIHelpers.xlam. In that add-in is a CAppEvents class for controlling application level events. One event that I’m now using is the Application_WorkbookNewSheet event. It listens for when a new sheet is added to any workbook.

Private Sub mxlApp_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)

    If Sh.Index = Wb.Sheets.Count 1 Then

        Sh.Move , Wb.Sheets(Wb.Sheets.Count)

    End If

End Sub

If the new sheet is the penultimate sheet, move it to the end. When I’m on the last sheet and insert a new sheet, more often than not I want the new sheet to be to the right. There are a few times when that’s not true and I’ll have to move them. But this will cut down on manually moving worksheets significantly.

Insert a worksheet

  • Select the New Sheet plus icon Select at the bottom of the workbook.

  • Or, select Home > Insert > Insert Sheet.

    Insert Cells

Rename a worksheet

  • Double-click the sheet name on the Sheet tab to quickly rename it.

  • Or, right-click on the Sheet tab, click Rename, and type a new name.

Move a worksheet

  • To move the tab to the end, right-click the Sheet tab then Move or Copy > (move to end) > OK .

  • Or, click and drag to tab to any spot.

Delete a worksheet

  • Right-click the Sheet tab and select DeleteDelete.

  • Or, select the sheet, and then select Home > Delete > Delete Sheet.

    Delete

Note: Sheet tabs are displayed by default. If you don’t see them, click Options > Advanced > Display options for this workbook > Show Sheet tabs.

To insert a new worksheet, do one of the following:

  • To quickly insert a new worksheet at the end of the existing worksheets, click the Insert Worksheet tab at the bottom of the screen.

    Sheet tabs

  • To insert a new worksheet in front of an existing worksheet, select that worksheet and then, on the Home tab, in the Cells group, click Insert, and then click Insert Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the tab of an existing worksheet, and then click Insert. On the General tab, click Worksheet, and then click OK.

    Note: To change the order of the worksheets in a workbook, click the tab of the worksheet that you want to move, and then drag it to the location that you want.

What do you want to do?

  • Insert multiple worksheets at the same time

  • Change the default number of worksheets in a new workbook

  • Insert a new sheet that is based on a custom template

  • Rename a worksheet

  • Delete one or more worksheets

Insert multiple worksheets at the same time

  1. Hold down SHIFT, and then select the same number of existing sheet tabs of the worksheets that you want to insert in the open workbook.

    For example, if you want to add three new worksheets, select three sheet tabs of existing worksheets.

  2. On the Home tab, in the Cells group, click Insert, and then click Insert Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the selected sheet tabs, and then click Insert. On the General tab, click Worksheet, and then click OK.

  3. To change the order of the worksheets in a workbook, click the tab of the worksheet that you want to move, and then drag it to the location that you want.

Change the default number of worksheets in a new workbook

  1. Click the File tab.

    What and where is the Microsoft Backstage Button?

    For more information about the Microsoft Backstage Button, see What and where is the Backstage?

  2. Under Excel, click Options.

  3. In the General category, under When creating new workbooks, in the Include this many sheets box, enter the number of sheets that you want to include by default when you create a new workbook.

  4. Click any other tab to return to your file.

Insert a new sheet that is based on a custom template

  1. If needed, create the worksheet template that you want to base a new worksheet on.

    How to create a worksheet template

    1. Select the worksheet that you want to use as a template.

    2. Click the File tab.

    3. Under Info, click Save As.

    4. In the File name box, type the name of the worksheet template.

      • To create a custom worksheet template, type the file name that you want to use.

      • To create the default worksheet template, type sheet.

        Note: Custom templates are automatically saved in the Templates folder. The default worksheet template, sheet.xltx or sheet.xltm, should be saved in the XLStart folder, which is usually C:Program FilesMicrosoft OfficeOffice14XLStart.

    5. Do one of the following:

      • On a computer that is running Windows Vista, in the list, click Excel Template or Excel Macro-Enabled Template.

      • On a computer that is running Microsoft Windows XP, in the Save as type box, click Excel Template or Excel Macro-Enabled Template.

    6. Click Save.

  2. Right-click the sheet tab of a worksheet, and then click Insert.

  3. Double-click the template for the type of sheet that you want.

Rename a worksheet

  1. On the Sheet tab bar, right-click the sheet tab that you want to rename, and then click Rename Sheet.

    Sheet tabs with Sheet2 selected

  2. Select the current name, and then type the new name.

    Tip: You can include the name of the sheet when you print the worksheet.

    How to print sheet names

    1. On the Insert tab, in the Text group, click Header & Footer.

    2. In the Page Layout View, click the location where you want the sheet name to appear.

    3. In the Header & Footer elements group, click Sheet Name Button image.

Delete one or more worksheets

  1. Select the worksheet or worksheets that you want to delete.

    Tip: When multiple worksheets are selected, [Group] appears in the title bar at the top of the worksheet. To cancel a selection of multiple worksheets in a workbook, click any unselected worksheet. If no unselected sheet is visible, right-click the tab of a selected sheet, and then click Ungroup Sheets on the shortcut menu.

  2. On the Home tab, in the Cells group, click the arrow next to Delete, and then click Delete Sheet.

    The Cells group on the Home tab

    Tip: You can also right-click the sheet tab of a worksheet or a sheet tab of any selected worksheets that you want to delete, and then click Delete Sheet.

8 ответов

Попробуйте следующее:

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

Или используйте предложение With, чтобы избежать неоднократного вызова вашего объекта

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

Выше может быть дополнительно упрощено, если вам не нужно вызывать на том же рабочем листе в остальной части кода.

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub

L42
20 дек. 2013, в 07:01

Поделиться

Пожалуйста, используйте этот один вкладыш:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"

Amar
03 янв. 2016, в 06:24

Поделиться

Попробуйте следующее:

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

Mr F
07 окт. 2014, в 12:45

Поделиться

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(при добавлении листа, в любом случае это будет активный лист)

Saptarshi
14 сен. 2015, в 09:11

Поделиться

Попробуйте использовать:

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

Если вы хотите проверить, существует ли листок с тем же именем, вы можете создать функцию:

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

Когда функция будет создана, вы можете вызвать ее из основного Sub, например:

Sub main

    funcCreateList "MySheet"

Exit Sub

Ivan Tokarev
23 март 2016, в 10:24

Поделиться

Попробуйте переключить порядок кода. Сначала вы должны создать рабочий лист, чтобы назвать его.

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

спасибо,

Developer
15 нояб. 2016, в 19:44

Поделиться

Это даст вам возможность:

  • Перезаписать или сохранить вкладку с тем же именем.
  • Поместите лист на конец всех вкладок или рядом с текущей вкладкой.
  • Выберите свой новый лист или активный.

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
17 окт. 2017, в 22:40

Поделиться

Это быстрое и простое добавление именованной вкладки к текущему листу:

Sheets.Add.Name = "Tempo"

Jan
22 окт. 2015, в 20:37

Поделиться

Ещё вопросы

  • 0Изменение согласованного правила CSS
  • 1Запросить данные области, содержащиеся в другом объекте
  • 0хранить вывод boost :: bind в boost :: function
  • 1Заголовок навигационного ящика не скрывается
  • 1Обнаружить нажатие клавиши в Python не работает
  • 1Вычисление n-го корня из p с использованием BigDecimals
  • 0Группировка по средним интервалам на таймфрейме
  • 0MySQL поиск значения в двух столбцах и сумма третьего столбца
  • 0AngularJs: NgMessages не будет принимать фигурные скобки
  • 0Нажав на Sumbit, я перехожу на страницу php.
  • 1ошибка памяти при иерархической кластеризации Python 3.6
  • 1как использовать строитель строк для добавления двойных кавычек и ‘ИЛИ’ между элементами
  • 1Внедрение disqus в мобильном приложении
  • 1Mac: AVD не запустится
  • 0Сделать текстовое поле и изображение вызвать DatePicker
  • 1Как я могу воспроизвести mp3-файл с помощью команды adb с помощью Google Play Music на Android KitKat 4.4.4?
  • 0PHP Пустая папка не удаляется с помощью команды rmdir
  • 1Загружать локальные изображения с внешнего сайта в iframe в приложении Electron
  • 1Создать массив значений из вложенного объекта, используя _Underscore
  • 1Элемент ContextMenuStrip, созданный в DataGridViewCellMouseEventHandler, содержит данные из предыдущего нажатия.
  • 0Как изменить Mysql-запрос (GROUP BY) Ошибка с sql_mode = only_full
  • 0PHP: корзина пуста после нажатия кнопки добавления
  • 1Анимация NineOldAndroids не работает на API> 10
  • 1div вращается, но окно обрезки div не
  • 0Текст в закругленных углах и зависание не работает
  • 1Чтобы узнать количество рабочих дней между двумя датами в linq
  • 0mysql_fetch_assoc проблема в цикле while — неправильный формат запроса в цикле foreach
  • 1Как заменить лямбда-функцию на частичную функцию? [Дубликат]
  • 1Несколько ключевых слов поиска по списку списков
  • 0MySQL Выберите СУММУ Итого Транзакции
  • 1Сравнение универсальных шаблонов: универсальный IEnumerable <>, который является универсальным, но соответствует всем определенным типам (IEnumerable <int>, IEnumerable <object>,…)?
  • 0Сложность анализа текста из файла
  • 0Blur событие запускается вместо клика
  • 0Как показать / скрыть Div на основе выпадающего выбора с помощью угловых?
  • 1Преобразование блоков ObjC в C # Lambdas
  • 0Проблема с кислородом при инициализации массива C ++
  • 1Используйте научную нотацию для графиков Python по умолчанию
  • 0Сохранение значений в виде просмотров на странице (посте) для пользователей, которые не вошли в систему?
  • 0AngularJS $ http не работает в IISExpress
  • 0app.js не работает в backbone.js + require.js
  • 1Я не могу получить действие просмотра в Gmail при отправке электронной почты с использованием почтового API Java
  • 0сортировка слиянием неверный вывод
  • 1EF Fluent Mapping — сопоставить поле коллекции из другой таблицы
  • 0«Страница 404 не найдена» на каждой странице с кодом
  • 0std :: ifstream бросает ошибку в Xcode 5
  • 0Получить все разговоры от одного пользователя в разных чатах
  • 0SQL ORDER BY FIELD () использовать массив
  • 1Разрешить объекту Number быть нулевым в Tapestry BeanEditor
  • 0Решите, когда Promise готов
  • 0Несколько операторов для оператора вопросительного знака

Excel VBA is a great tool for manipulating everything that is in your sheets. It is also a great way to manipulate the sheets themselves, and workbooks as well.

In the example below, we will show how to add a sheet at the end of our sheets list.

For our example, we will presume that we have three sheets in our workbook, which are called simply by their generic names: Sheet1, Sheet2, and Sheet3:

Now, we can simply click on the plus sign to add another sheet. However, if we would go to Sheet2 and then click on the plus sign, it would automatically add a sheet between Sheet2 and Sheet3, so not on the end of our list, where we want it.

For this and many more reasons, we can use VBA to automatically create the sheet at the end. To insert our code, we need to go to the VBA editor. To do so, we press ALT + F11 on our keyboard. After that, on the window that appears, we will right-click on the left window and choose Insert >> Module:

Once clicked, we will be presented with the clear text field, in which we will insert the following code:

Sub AddSheetsAtTheEnd()

    Sheets.Add After:=Sheets(Sheets.Count)

End Sub

This is what our code looks like in the editor:

It is one line of code. Once you type in “Sheets.Add” and press space, you will be presented with the options for adding your sheet:

You can see that we can add sheets before or after a certain object. We can also count the number of objects and then add ours. For our example, we use the “After” option, and then we count the total number of already existing sheets. This guarantees that the added sheet is always in the last place. We will add one more line of code, right above the End Sub:

ActiveSheet.Name = «Latest Sheet»

We know that the created sheet will be the one active, so we can use the line above to give this sheet a proper name.

Once we execute our code, this is the result we get:

Now, if we would try to execute the same code again, this is the message we would get:

Excel warns us that we cannot have two sheets with the same name. Our sheet will, however, be added. We will delete this sheet. Of course, we did not have to add the last line of code and give the name to our new sheet. When we delete this line of code, we will get a new sheet with a generic name:

Post Views: 420

Понравилась статья? Поделить с друзьями:
  • Excel add in vsto
  • Excel add in project
  • Excel add in javascript
  • Excel add in for pivot tables
  • Excel add in enable