Перейти к основному содержанию

Как автоматически вставить новую пустую строку с помощью командной кнопки в Excel?

Во многих случаях вам может потребоваться вставить новую пустую строку в указанную позицию вашего рабочего листа. В этой статье мы покажем вам, как автоматически вставить новую пустую строку, нажав кнопку Command в Excel.

Автоматическая вставка новой пустой строки с помощью командной кнопки


Автоматическая вставка новой пустой строки с помощью командной кнопки

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

1. Во-первых, вам нужно вставить командную кнопку. Пожалуйста, нажмите Застройщик > Вставить > Командная кнопка (элемент управления ActiveX). Смотрите скриншот:

2. Затем нарисуйте командную кнопку на листе, в котором вам нужно добавить новые строки, щелкните правой кнопкой мыши кнопку и нажмите Объекты из контекстного меню.

3. в Объекты диалоговом окне введите отображаемый текст командной кнопки в поле Подпись поле под Категории вкладку, а затем закройте диалоговое окно.

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

4. Снова щелкните правой кнопкой мыши командную кнопку, а затем щелкните Просмотреть код из контекстного меню.

5. Затем Microsoft Visual Basic для приложений окна, замените исходный код приведенным ниже кодом VBA в Code окно.

Код VBA: автоматически вставлять пустую новую строку с помощью командной кнопки

Private Sub CommandButton1_Click()
    Dim rowNum As Integer
    On Error Resume Next
    rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
                                    Title:="Kutools for excel", Type:=1)
    Rows(rowNum & ":" & rowNum).Insert Shift:=xlDown
End Sub

Внимание: В коде CommanButton1 - это имя созданной вами командной кнопки.

6. Нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно. И выключите Режим проектирования под Застройщик меню.

7. Щелкните вставленную кнопку управления и нажмите Kutools for Excel всплывает диалоговое окно. Введите номер определенной строки, в которую вы хотите добавить новую пустую строку, а затем щелкните значок OK кнопка. Смотрите скриншот:

Затем новая пустая строка вставляется в указанную позицию вашего рабочего листа, как показано ниже. И он сохраняет форматирование ячейки выше.


Статьи по теме:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


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

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (26)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Bedankt voor je uitleg. Ik heb de formule toegepast maar bekom dat ik maar 1 lijn kan toevoegen. Daarna laat de knop het niet meer toe en moet ik eerst mijn toegevoegde rij verwijderen. Is er een manier om dit aan te passen?
This comment was minimized by the moderator on the site
Is there a way to make to row inset always below the last entry?
This comment was minimized by the moderator on the site
How do I do the opposite of this and create a button that will delete a row?
This comment was minimized by the moderator on the site
Hi Big Ant,

Here's the modified code to delete a specified row when the Command Button is clicked:


Private Sub CommandButton1_Click()
'Updated by Extendoffice 20230817
    Dim rowNum As Integer
    On Error Resume Next
    rowNum = Application.InputBox(Prompt:="Enter Row Number which you want to delete:", _
                                    Title:="Kutools for excel", Type:=1)
    If rowNum <> 0 Then
        Rows(rowNum).Delete Shift:=xlUp
    End If
End Sub
This comment was minimized by the moderator on the site
Criei uma linha e nomeei como spotB,
Mudei a altura da linha para 0,01 para ocultá-la (apenas por estética).
Criei um botão:
Application.Goto Reference:="spotB"
Selection.EntireRow.Insert

Problema resolvido.

Obrigado pelos códigos a Mah e crystal, mas eu tinha 8 títulos para separar, cada um inserindo linhas quando necessário ao usuário, e não queria nenhuma pergunta sobre quantidade de linhas, os usuários não leem perguntas e clicam logo em OK, depois reclamam...
This comment was minimized by the moderator on the site
... Testei os códigos acima, mas, como se trata de pessoas que vão usar, não é viável os box que pedem a linha e a quantidade, não dá...
This comment was minimized by the moderator on the site
Caros colegas, após pesquisar (bastante) na net não consegui encontrar um atalho, comando, código, nada, nada, que eu possa usar para inserir em uma macro APENAS uma forma de inserir uma linha ABAIXO da célula ativa. Isto porquê se eu gravar o endereço da célula, ele não muda, fica sempre na mesma célula e as seguintes não vão ficar corretamente abaixo, e se eu usar um endereço de célula fixo, a linha tem que ser inserida acima, mas não formata da forma desejada, que seria o formato das linhas de cima.

Acho que o código existe, só não encontro, já tentei várias formas, selecionando um fixo, subindo uma linha e pedindo para inserir após, mas as seguintes não funcionam de acordo.

Alguém poderia me ajudar?
This comment was minimized by the moderator on the site
Hi

I used the code but wanted to add rows with formulas, therefore I added the last line to be able to add the rows with formulas.
However, in my excel file and in column "F" I have a text which can be entered manually and would be different in different cases. Therefore, I would like to add rows below the reference row with keeping the formulas and values in all cells except the cell from column "F" which I would like to be copied as blank!
Could you please help me with what should I add to the underneath code to be able to have the cells of column "F" blank whenever I add a row with this code?
thanks in advance!

Private Sub CommandButton1_Click()
Dim xIntRrow As Integer
Dim rowNum As Integer
On Error Resume Next
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="Kutools for excel", Type:=1)
xIntRrow = Application.InputBox(Prompt:="Type in the number of rows you want to insert", _
Title:="Kutools for excel", Type:=1)
Rows(rowNum + 1 & ":" & rowNum + 1).EntireRow.Resize(xIntRrow).Insert Shift:=xlShiftDown
Rows(rowNum).Resize(xIntRrow + 1).FillDown

End Sub
This comment was minimized by the moderator on the site
Hi Mah,
The following VBA code may do you a favor. Please give it a try. Thank you.

Private Sub CommandButton1_Click()
'Updated by Extendoffice 20220707
    Dim rowNum As Integer
    Dim xRg1, xRg2 As Range
    
    On Error Resume Next
    
    rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
                                    Title:="Kutools for excel", Type:=1)
    
    Rows(rowNum & ":" & rowNum).Insert Shift:=xlDown
    Rows((rowNum - 1) & ":" & (rowNum - 1)).Copy
    Rows(rowNum & ":" & rowNum).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False
    Range("F" & rowNum).Value = ""
End Sub
This comment was minimized by the moderator on the site
Sub AddNewRow()



Private Sub CommandButton1_Click()

ActiveSheet.Unprotect Password:="1234"



Dim mySheets

Dim i As Long



mySheets = Array("Sheet2")



For i = LBound(mySheets) To UBound(mySheets)

With Sheets(mySheets(i))

.Range("B10").EntireRow.Insert Shift:=xlDown

.Range("B10:H10").Borders.Weight = xlThin

End With

Next i



ActiveSheet.Protect Password:="1234"



End Sub

I don't know if this will work for you. It worked quite well for me. I even left unprotected cells that you can input data and the formulas are still active. Took me a whole day to figure it out. replace "1234" with whatever password you feel like, "Sheet2" with the Sheet you are working with and input the range you want.
The code first unprotects the worksheet, adds row and protects the worksheet.
This comment was minimized by the moderator on the site
is it possible to create in a different sheet? I really need that
This comment was minimized by the moderator on the site
can possible insert multiple sheet row at one time click by this .
This comment was minimized by the moderator on the site
Hi,
The below code can help you solve the problem. Please have a try.

Private Sub CommandButton1_Click()
Dim xIntRrow As Integer
Dim rowNum As Integer
On Error Resume Next
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="Kutools for excel", Type:=1)
xIntRrow = Application.InputBox(Prompt:="Type in the number of rows you want to insert", _
Title:="Kutools for excel", Type:=1)
Rows(rowNum + 1 & ":" & rowNum + 1).EntireRow.Resize(xIntRrow).Insert Shift:=xlShiftDown

End Sub
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations