Перейти до основного матеріалу

Як швидко об’єднати сусідні рядки з однаковими даними в Excel?

Припустимо, у вас є робочий аркуш з однаковими даними в сусідніх рядках, і тепер ви хочете об’єднати ті самі комірки в одну комірку, щоб дані виглядали акуратно і красиво. Як швидко та зручно об’єднати сусідні рядки з однаковими даними? Сьогодні я познайомлю вас із швидким способом вирішення цієї проблеми.


Об’єднайте сусідні рядки однакових даних із кодом VBA

Звичайно, ви можете об'єднати ті самі дані з Злиття та центр команда, але якщо є сотні комірок, які потрібно об’єднати, цей метод буде трудомістким. Отже, наступний код VBA може допомогти вам легко об’єднати ті самі дані.

1. Утримуйте клавішу ALT + F11 і відкриває Microsoft Visual Basic для додатків вікна.

2. Клацання Insert > Модуліта вставте наступний макрос у Модулівікна.

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. Потім натисніть F5 для запуску цього коду, на екрані відображається діалогове вікно для вибору діапазону для роботи. Дивіться знімок екрана:

doc злиття тих самих комірок 2

4. Потім натисніть OK, ті самі дані у стовпці A будуть об’єднані разом. Дивіться знімок екрана:

doc злиття тих самих комірок 1


Об’єднайте суміжні рядки однакових даних за допомогою Kutools для Excel

З Об’єднати ті самі комірки корисність Kutools для Excel, Ви можете швидко об’єднати однакові значення в декількох стовпцях одним клацанням миші.

Kutools для Excel : з більш ніж 300 зручними надбудовами Excel, які можна спробувати без обмежень протягом 30 днів. 

після установки Kutools для Excel, Ви можете зробити наступне:

1. Виберіть стовпці, для яких потрібно об’єднати сусідні рядки з однаковими даними.

2. Клацання Кутулс > Злиття та розділення > Об’єднайте ті самі клітини, див. скріншот:

3. А потім ті самі дані у вибраних стовпцях були об’єднані в одній комірці. Дивіться знімок екрана:

doc злиття тих самих комірок 4

Натисніть, щоб завантажити Kutools для Excel та безкоштовну пробну версію зараз!

Щоб дізнатись більше про це, відвідайте це Об’єднайте ті самі клітини функцію.


Демонстрація: Об’єднайте ті самі комірки в одну комірку або об’єднайте, щоб заповнити повторювані значення:

Kutools для Excel: з більш ніж 300 зручними надбудовами Excel, спробуйте безкоштовно без обмежень протягом 30 днів. Завантажте та безкоштовно пробну версію зараз!

Найкращі інструменти продуктивності офісу

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

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
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