Ir para o conteúdo principal

Como mesclar rapidamente linhas adjacentes com os mesmos dados no Excel?

Suponha que você tenha uma planilha com os mesmos dados nas linhas adjacentes e agora queira mesclar as mesmas células em uma célula, para que os dados pareçam organizados e bonitos. Como você mescla linhas adjacentes com os mesmos dados de forma rápida e conveniente? Hoje, vou apresentar a vocês uma maneira rápida de resolver esse problema.


Mesclar linhas adjacentes dos mesmos dados com o código VBA

Claro, você pode mesclar os mesmos dados com Unir e centrar comando, mas se houver centenas de células que precisam ser mescladas, esse método será demorado. Portanto, o seguinte código VBA pode ajudá-lo a mesclar os mesmos dados facilmente.

1. Segure o ALT + F11 chaves, e abre o Microsoft Visual Basic para Aplicações janela.

2. Clique inserção > Móduloe cole a macro a seguir no Módulojanela.

Sub MergeSameCell()
'Updateby Extendoffice
Dim Rng As Range, xCell As Range
Dim xRows As Integer
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
xRows = WorkRng.Rows.Count
For Each Rng In WorkRng.Columns
    For i = 1 To xRows - 1
        For j = i + 1 To xRows
            If Rng.Cells(i, 1).Value <> Rng.Cells(j, 1).Value Then
                Exit For
            End If
        Next
        WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1)).Merge
        i = j - 1
    Next
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

3. Em seguida, pressione o botão F5 para executar este código, uma caixa de diálogo é exibida na tela para selecionar um intervalo para trabalhar. Veja a imagem:

doc mesclar as mesmas células 2

4. Então clique OK, os mesmos dados na coluna A serão mesclados. Veja a imagem:

doc mesclar as mesmas células 1


Mesclar linhas adjacentes dos mesmos dados com o Kutools para Excel

Com o Mesclar mesmas células utilidade de Kutools for Excel, você pode mesclar rapidamente os mesmos valores em várias colunas com um clique.

Kutools for Excel : com mais de 300 suplementos úteis do Excel, grátis para testar sem limitação em 30 dias. 

Depois de instalar Kutools for Excel, você pode fazer o seguinte:

1. Selecione as colunas que deseja mesclar com as linhas adjacentes com os mesmos dados.

2. Clique Kutools > Unir e dividir > Mesclar as mesmas células, veja a captura de tela:

3. E então os mesmos dados nas colunas selecionadas foram mesclados em uma célula. Veja a imagem:

doc mesclar as mesmas células 4

Clique para baixar o Kutools para Excel e testar gratuitamente agora!

Para saber mais sobre isso, visite este Mesclar as mesmas células recurso.


Demonstração: mesclar as mesmas células em uma célula ou desfazer a mesclagem para preencher os valores duplicados:

Kutools for Excel: com mais de 300 suplementos úteis do Excel, grátis para testar sem limitação em 30 dias. Baixe e teste grátis agora!

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 (44)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
This helped me a lot. Searched a lot of sites, even Chat GPT too. But this code right here is the one. I had like thousands of data which i wanted to merge according to the data in one single column. This code helped me out. Kudos to you my good Sir!
This comment was minimized by the moderator on the site
thanks alot
This comment was minimized by the moderator on the site
How can I exit the running macro when I want to cancel the cell selection when I run the macro?
This comment was minimized by the moderator on the site
Hello, Murat,
The vba code in this article will pop out an error dialog box if you click the Cancel button, to fix this problem, please apply the below code:
Sub MergeSameCell()
'Updateby Extendoffice
On Error Resume Next
Dim Rng As Range, xCell As Range
Dim xRows As Integer
xTitleId = "KutoolsforExcel"
Set workrng = Application.Selection
Set workrng = Application.InputBox("Range", xTitleId, workrng.Address, Type:=8)
If workrng Is Nothing Then
Exit Sub
End If
Application.ScreenUpdating = False
Application.DisplayAlerts = False
xRows = workrng.Rows.Count
For Each Rng In workrng.Columns
    For i = 1 To xRows - 1
        For j = i + 1 To xRows
            If Rng.Cells(i, 1).Value <> Rng.Cells(j, 1).Value Then
                Exit For
            End If
        Next
        workrng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1)).Merge
        i = j - 1
    Next
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub



Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Hi Guys!
First of all thank you for all your support. This has been amazing and worked in past. But for some reason it is not working anymore...

My range at the moment is "$A$2:$A$126551" I am not sure if this was so large before as per user the range was larger in past as well( I am trying to help him out here). Any assistance would be great.

I get the error:
"Run-time error '6':

Overflow"

on "xRows = WorkRng.Rows.Count"

Sub MergeSameCell()
'Updateby Extendoffice
Dim Rng As Range, xCell As Range
Dim xRows As Integer
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
xRows = WorkRng.Rows.Count
For Each Rng In WorkRng.Columns
For i = 1 To xRows - 1
For j = i + 1 To xRows
If Rng.Cells(i, 1).Value <> Rng.Cells(j, 1).Value Then
Exit For
End If
Next
WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1)).Merge
i = j - 1
Next
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Additionally: When I select single date range upto row count 12547 it works but thats only for single date. I am looking to do it for all the dates in the column
This comment was minimized by the moderator on the site
Hi,
this has been amazing and worked in past. But for some reason it is not working anymore...

My range at the moment is "$A$2:$A$126551" I am not sure if this was so large before as per user the range was larger in past as well( I am trying to help him out here). Any assistance would be great.

I get the error:
"Run-time error '6':
Overflow"

on "xRows = WorkRng.Rows.Count"<sup></sup><strike></strike>
Sub MergeSameCell()
'Updateby Extendoffice
Dim Rng As Range, xCell As Range
Dim xRows As Integer
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
xRows = WorkRng.Rows.Count
For Each Rng In WorkRng.Columns
For i = 1 To xRows - 1
For j = i + 1 To xRows
If Rng.Cells(i, 1).Value <> Rng.Cells(j, 1).Value Then
Exit For
End If
Next
WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1)).Merge
i = j - 1
Next
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Thanks a lot for this macro, you saved my day, really!
This comment was minimized by the moderator on the site
A formula funciona perfeitamente para valores em colunas, mas se fossem valores para mesclar em linhas? Como seria a formula? Obrigado!!
This comment was minimized by the moderator on the site
Thanks a lot for the help. I have a followup question on this. Suppose i have the following situation:

Apple 2
Apple 2
Orange 2
Orange 2
Banana 1
Pear 1
Kiwi 1

Running the macro will cause all the '1's and the '2's to be grouped together and my total count will be 3 instead of 7. Is there a way I can merge the cells in the second column based on those in the first? Thanks in advance (:
This comment was minimized by the moderator on the site
I have the same problem, I want merge the cells in a column based on the value of another column.. Is there a solution?
This comment was minimized by the moderator on the site
This is amazing. Thank you so much for the code. Is there any addition that would make it so the segments do not merge over a page break when printing?
This comment was minimized by the moderator on the site
Hello, Kimberly,
I can't get your detailed problem, but, the below VBA code can help you to merge the same cells before and after the page break separately, please try.
If it helps you, please let me know.

Sub MergeSameCell_PageBreak()
Dim Rng As Range, xCell As Range
Dim xRows As Integer
Dim xHPB As HPageBreaks
Dim xChpb As Long
Dim xBol As Boolean
Dim xRg As Range
Set xHPB = ActiveSheet.HPageBreaks
xChpb = xHPB.Count
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
xRows = WorkRng.Rows.Count
For Each Rng In WorkRng.Columns
For I = 1 To xRows - 1
For J = I + 1 To xRows
xBol = False
Set xRg = Rng.Cells(J, 1)
For xC = 1 To xChpb
If xRg.Row = xHPB.Item(xC).Location.Row Then
xBol = True
Exit For
End If
Next
If xBol Then Exit For
If Rng.Cells(I, 1).Value <> Rng.Cells(J, 1).Value Then
Exit For
End If
Next
WorkRng.Parent.Range(Rng.Cells(I, 1), Rng.Cells(J - 1, 1)).Merge
I = J - 1
Next
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
In the above VBA code line number 19 "i=j-1 "
how is it going to affect our logic anyway? I did remove that and could still able to get the same result!
Any specific purpose why it is present?
This comment was minimized by the moderator on the site
It is to limit the value i to last row.
Please disregard this post!
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