To merge cells with the same value in Excel using VBA, you must write a loop that iterates through a selected range from the bottom up, comparing each cell to the one above it; if the values match, the code merges them and centers the text. This process is essential for cleaning up reports, creating visual hierarchies in data tables, and removing the repetitive look of duplicated entries in a column without manually clicking the Merge & Center button hundreds of times.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • A dataset with repeating values in a single column that you wish to consolidate.
  • The Developer tab enabled in the Excel Ribbon (if not visible, right-click any tab, select Customize the Ribbon, and check the Developer box).
  • A backup copy of your workbook, as VBA actions cannot be undone using the Undo (Ctrl+Z) button.

Step-by-Step

  1. Open the Visual Basic Editor: Open your Excel workbook. Press Alt + F11 on your keyboard to launch the Visual Basic for Applications (VBA) editor window.
  2. Insert a New Module: In the VBA editor, go to the top menu and select Insert > Module. This creates a blank white space where you can paste your custom script.
  3. Enter the VBA Code: Copy and paste the following code into the module window:
    Sub MergeSameValues()
            Dim rng As Range
            Dim cell As Range
            Dim mergeStart As Range
            
            ' Optimize performance
            Application.ScreenUpdating = False
            Application.DisplayAlerts = False
            
            ' Set the range to the current selection
            Set rng = Selection
            
            ' Loop from the bottom of the selection upwards
            For i = rng.Rows.Count To 2 Step -1
                Set cell = rng.Cells(i, 1)
                
                ' Check if current cell value matches the cell above it
                If cell.Value = cell.Offset(-1, 0).Value Then
                    ' Merge the cell with the one above it
                    Range(cell.Offset(-1, 0), cell).Merge
                End If
            Next i
            
            ' Center the text vertically and horizontally for a clean look
            With rng
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
            
            Application.DisplayAlerts = True
            Application.ScreenUpdating = True
            
            MsgBox "Merging Complete!", vbInformation
        End Sub
  4. Select Your Data: Close the VBA editor window to return to your Excel sheet. Use your mouse to highlight the specific range of cells in the column that you want to merge. Be careful to select only the cells containing the values you want to consolidate.
  5. Run the Macro: With the cells still selected, press Alt + F8. Select MergeSameValues from the list of available macros and click Run.
  6. Verify the Results: Excel will process the column. Once the "Merging Complete!" message appears, check your data to ensure that only identical consecutive values were merged and that the formatting is centered.

Common Mistakes

One of the most frequent errors is attempting to run the macro on a range that contains empty cells. If the code encounters two empty cells in a row, it treats them as having the "same value" and merges them. This can lead to unexpected large gaps in your data. To avoid this, ensure your data is filtered or cleaned of blanks before running the script.

Another common mistake is selecting the entire column (by clicking the column letter at the top) rather than just the data range. Because Excel columns contain over a million rows, the macro will attempt to check every single cell, which can cause the program to freeze or crash. Always select only the specific cells that contain data.

Users also frequently forget to disable DisplayAlerts. By default, whenever Excel merges cells that both contain data, it triggers a warning popup stating that "Merging cells only keeps the upper-left value and discards other values." If you are merging 500 groups of cells, you would have to click "OK" 500 times. The code provided above includes Application.DisplayAlerts = False to bypass this annoyance.

Finally, attempting to use this macro on a Table (formatted via Ctrl+T) will result in an error. Excel Tables do not support merged cells by design. If your data is in a Table, you must first convert it back to a normal range by going to Table Design > Convert to Range.

Tips

To make this tool more accessible for other users of your workbook, you can assign the macro to a button. Go to the Developer tab, select Insert, choose the Button (Form Control), and draw it on your sheet. When prompted, assign it to the MergeSameValues macro. Now, anyone can merge the selected cells with a single click.

If you have a very large dataset, the Application.ScreenUpdating = False line is critical. It prevents Excel from redrawing the screen every time a merge happens, which can speed up the execution time from several minutes to a few seconds.

For those who want more control over the look, you can modify the alignment section of the code. For example, if you prefer the text to stay at the top of the merged block, change .VerticalAlignment = xlCenter to .VerticalAlignment = xlTop.

Always remember to save your file as an Excel Macro-Enabled Workbook (.xlsm). If you save it as a standard .xlsx file, all your VBA code will be permanently deleted when you close the workbook.

Troubleshooting

If the macro does not run and you see a "Macros are disabled" warning, you need to adjust your security settings. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings. Select "Disable VBA macros with notification." This allows you to choose to enable macros each time you open the file.

If the code is running but not merging cells that look identical, check for hidden spaces. A cell containing "Apple" and a cell containing "Apple " (with a trailing space) are not considered the same value by VBA. You can fix this by using the =TRIM() function on your data before running the macro to remove unnecessary whitespace.

If Excel becomes unresponsive (Not Responding) during the process, it is likely because you selected too many rows. Press Ctrl + Break or Esc to attempt to stop the code. If that fails, you may need to force-close Excel via the Task Manager. To prevent this, reduce the size of your selection or process the data in smaller chunks.

If you receive a "Type Mismatch" error, it usually happens when the range contains a mix of error values (like #N/A or #VALUE!) and text. The code cannot compare an error value to a string. You must resolve the errors in your spreadsheet using IFERROR or by manually deleting the errors before running the macro.

Frequently Asked Questions

Can I unmerge the cells after running the macro?

You cannot use the standard Undo button. To unmerge, you must select the range and click the "Merge & Center" button in the Home tab to toggle it off. However, this will leave you with only one value per group; the other cells will be blank.

Will this macro delete my data?

Yes, in a sense. When Excel merges cells, it only keeps the value of the top-left cell and deletes the values in the other cells being merged. Since the macro only merges cells with the same value, no unique information is lost, but the redundant data is removed.

Does this work on Mac versions of Excel?

Yes, the provided VBA code is compatible with Excel for Mac. The keyboard shortcuts for the VBA editor may differ (use the Tools menu or the Developer tab), but the logic of the code remains the same.

Can I merge cells across multiple columns at once?

The provided code is designed for a single column (the first column of your selection). If you select multiple columns, it will only process the leftmost column. To handle multiple columns, you would need to wrap the existing logic in another loop that iterates through rng.Columns.

How do I stop the macro from centering the text?

Simply delete or comment out (by adding an apostrophe at the start of the line) the section of the code that begins with With rng and ends with End With. This will keep your original cell alignment intact.