Ir para o conteúdo principal

Como inserir uma linha automaticamente com base no valor da célula no Excel?

doc-insert-row-based-on-value-1
Suponha que você tenha um intervalo de dados e queira inserir automaticamente as linhas em branco acima ou abaixo de um determinado valor no Excel, por exemplo, inserir automaticamente as linhas abaixo do valor zero, conforme mostrado a imagem abaixo. No Excel, não há uma maneira direta de resolver essa tarefa, mas posso introduzir um código Macro para você inserir linhas automaticamente com base em um determinado valor no Excel.
Insira a linha abaixo com base no valor da célula com VBA

Insira a linha acima com base no valor da célula com o Kutools para Excel boa ideia 3

Para inserir uma linha com base no valor da célula executando o VBA, siga as etapas abaixo:

1. Pressione Alt + F11 teclas simultaneamente, e um Microsoft Visual Basic para Aplicações janela pula para fora.

2. Clique inserção > Móduloe cole abaixo o código VBA no popping Módulo janela.

VBA: insira a linha abaixo com base no valor da célula.

Sub BlankLine()
	'Updateby20150203
	Dim Rng As Range
	Dim WorkRng As Range
	On Error Resume Next
	xTitleId                   = "KutoolsforExcel"
	Set WorkRng                = Application.Selection
	Set WorkRng                = Application.InputBox("Range", xTitleId, WorkRng.Address, Type: = 8)
	Set WorkRng                = WorkRng.Columns(1)
	xLastRow                   = WorkRng.Rows.Count
	Application.ScreenUpdating = False
	For xRowIndex = xLastRow To 1 Step - 1
		Set Rng                   = WorkRng.Range("A" & xRowIndex)
		If Rng.Value = "0" Then
			Rng.Offset(1, 0).EntireRow.Insert Shift: = xlDown
		End If
	Next
	Application.ScreenUpdating = True
End Sub

3. Clique F5 chave ou o Execute , uma caixa de diálogo é exibida e selecione a coluna que contém zero. Veja a imagem:
doc-insert-row-based-on-value-2

4. Clique OK. Então, linhas em branco serão inseridas abaixo do valor zero.
doc-insert-row-based-on-value-3

Dica:

1. Se você deseja inserir linhas com base em outro valor, você pode alterar 0 a qualquer valor que você deseja no VBA: Se Rng.Value = "0" então.

2. Se você deseja inserir linhas acima de zero ou outro valor, você pode usar o código vba abaixo.

VBA: Insira a linha acima do valor zero:

Sub BlankLine()
	'Updateby20150203
	Dim Rng As Range
	Dim WorkRng As Range
	On Error Resume Next
	xTitleId                   = "KutoolsforExcel"
	Set WorkRng                = Application.Selection
	Set WorkRng                = Application.InputBox("Range", xTitleId, WorkRng.Address, Type: = 8)
	Set WorkRng                = WorkRng.Columns(1)
	xLastRow                   = WorkRng.Rows.Count
	Application.ScreenUpdating = False
	For xRowIndex = xLastRow To 1 Step - 1
		Set Rng                   = WorkRng.Range("A" & xRowIndex)
		If Rng.Value = "0" Then
			Rng.EntireRow.Insert Shift: = xlDown
		End If
	Next
	Application.ScreenUpdating = True
End Sub

doc-insert-row-based-on-value-4


Se você não está familiarizado com o VBA, pode tentar Kutools for Excel's Selecione células específicas utilitário e insira as linhas acima.

Kutools for Excel, com mais de 300 funções úteis, tornam seus trabalhos mais fáceis. 

Depois de instalar Kutools para Excel, faça o seguinte:(Baixe gratuitamente o Kutools para Excel agora!)

1. Selecione a lista da qual deseja descobrir as células específicas e clique em Kutools > Selecionar > Selecione células específicas. Veja a imagem:
doc inserir linha com base no valor 9

2. Na caixa de diálogo pop-up, verifique Linha inteira opção e, em seguida, vá para selecionar É igual a da Tipo específico lista e insira o valor que deseja encontrar na caixa de texto correta. Veja a imagem:
doc inserir linha com base no valor 6

3. Clique Ok, e uma caixa de diálogo aparecerá para lembrá-lo do número de linhas selecionadas, basta fechá-la.

4. Coloque o cursor em uma linha selecionada e clique com o botão direito para selecionar inserção no menu de contexto. Veja a imagem:
doc inserir linha com base no valor 7

Agora as linhas são inseridas acima com base em um valor específico.
doc inserir linha com base no valor 8


Artigos relativos:

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
Comments (43)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hola mira necesito agregar filas en blanco automaticamente cuando se me produce desbordamiento en diferentes filas y probe varias formas y no lo toma.
me podrias ayudar?desde ya gracias
This comment was minimized by the moderator on the site
need help with a code. I am trying insert rows based on value in another cell on another worksheet (same workbook). then automatically update that number if blank cell if filled. so basically worksheet 1 has, column A all time starts from 4 am to 10 pm. Column B is employee name. Worksheet 2 has time starts in column A and available shifts for that time start in column B. I need to find a way to automatically insert blank row at last time start ie 4 am in worksheet 1 if worksheet 2 has ie. 1 available shift to pick up for 4 am. then update the number in worksheet 2 if the cell if fill at a later time. Is this possible?
This comment was minimized by the moderator on the site
Gracias por tu macro, he utilizado la primera y me funciona perfectamente.
Necesitaría a la vez de generar una fila en blanco debajo de otra dependiendo de un valor, que esa linea se copie en la que se ha generado en blanco.
Me seria de gran ayuda.
This comment was minimized by the moderator on the site
Can anyone suggest how to do this with adding 1 row for any number grater than 0?
This comment was minimized by the moderator on the site
Hi, Jordan, change the script: If Rng.Value = "0" Then to If Rng.Value > "0" Then
in the vba of the article.
This comment was minimized by the moderator on the site
Instead of a dialogue box that pops up asking which cells it should look at, how can I instead just require a preset range? In this case I want it to always run it for E3 to E800. Thanks!
This comment was minimized by the moderator on the site
Hi, Christopher M, try below code, it take A1:A10 as an example, just change it as you need.
Sub BlankLine()
'ByExtendoffice
Dim Rng As Range

Dim WorkRng As Range

Dim xRngI As Range

On Error Resume Next

xTitleId = "KutoolsforExcel"

Set WorkRng = Application.Range("A1:A10") 'Change the range as you need

Set WorkRng = WorkRng.Columns(1)

xLastRow = WorkRng.Rows.Count

Application.ScreenUpdating = False

For xRowIndex = xLastRow To 1 Step -1

  Set Rng = WorkRng.Range("A" & xRowIndex)

  If Rng.Value = "Node1" Then

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).Value = "Scanner"

    Rng.Offset(2, 0).Value = "Printer"

    Rng.Offset(3, 0).Value = "CD"

  End If

Next

Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
I need to add particular rows with values in them for specific cell contents, but not sure how to do so without having to manually do for over 3800+ lines

Ex: A1 = Node1
I need to have a row inserted and it to enter the value Scanner
Enter another row and enter the value Printer
another row with value CD.
Etc
This comment was minimized by the moderator on the site
Hi, Chris, here is a VBA can help you to automatically insert three rows (Scanner, Printer, CD) when the value equal to Node1.
Sub BlankLine()
'ByExtendoffice
Dim Rng As Range

Dim WorkRng As Range

Dim xRngI As Range

On Error Resume Next

xTitleId = "KutoolsforExcel"

Set WorkRng = Application.Selection

Set WorkRng = Application.InputBox("Select a range", xTitleId, WorkRng.Address, Type:=8)

Set WorkRng = WorkRng.Columns(1)

xLastRow = WorkRng.Rows.Count

Application.ScreenUpdating = False

For xRowIndex = xLastRow To 1 Step -1

  Set Rng = WorkRng.Range("A" & xRowIndex)

  If Rng.Value = "Node1" Then

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown

    Rng.Offset(1, 0).Value = "Scanner"

    Rng.Offset(2, 0).Value = "Printer"

    Rng.Offset(3, 0).Value = "CD"

  End If

Next

Application.ScreenUpdating = True

End Sub

Please let me know if works for you.
This comment was minimized by the moderator on the site
Hi,
Can this marco be used/altered for colored cells?
I need to insert at least 10 rows above end of the each series which are colored.
Thx!
This comment was minimized by the moderator on the site
please help mei have a data.i have one month time data, in that i have to insert a empty rows according to the escape time
This comment was minimized by the moderator on the site
Hi, hr.babu08, sorry the reply is late. I guess you want to insert blank rows or make a mark for the missing sequence data, if so, you can try Kutools for Excel's Find Missing Sequence Number feature.Here is the tutorial about the feature: https://www.extendoffice.com/product/kutools-for-excel/excel-find-missing-numbers-in-sequence.htmlIf you want other methods on inserting blank rows for missing sequence, please visit:https://www.extendoffice.com/documents/excel/3522-excel-find-missing-dates.html</div>;
This comment was minimized by the moderator on the site
Hello. The macro works for me but is there a way to always have the range/parameters set always to column J without the input box coming up at all? I would like it to skip the step of the input box coming up. Also, I have made sure that directly before this macro that the last line of my previous macro is Range("J:J").Select to make sure the whole J column is already selected.
This is what I have been using so far.

Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "Click OK to Continue"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Set WorkRng = WorkRng.Columns(1)
SendKeys "~"
xLastRow = WorkRng.Rows.Count
Application.ScreenUpdating = False
For xRowIndex = xLastRow To 1 Step -1
Set Rng = WorkRng.Range("A" & xRowIndex)
If Rng.Value = "New GMS Line" Then
Rng.EntireRow.Insert Shift:=xlDown
End If
Next


I Have tried experimenting using the SendKeys "~" command between some of the steps to try and get it to press enter automatically when the input box comes up but that hasn't worked either. I wasn't sure where exactly to use the SendKeys command in the macro or if it would even work with an input box!
This comment was minimized by the moderator on the site
Many thanks for this, really a tremendous time saver. Would it be possible to add some code which allows me to insert some text in the new row. For example i'm inserting new rows based on target value 'x', then i want to add text value 'y' in the cell below target value 'x'. Is this possible?
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