当值相同时,如何合并同一行VBA中的相邻单元格?

时间:2019-04-02 14:57:25

标签: excel vba merge

我是excel上VBA的初学者,所以我需要帮助。

我必须合并同一列中的相邻单元格,它们是范围变量,因为它总是会变化。

下图显示了我想要实现的目标:

enter image description here

1 个答案:

答案 0 :(得分:0)

就像建议的那样,您需要循环遍历各列,并确定重复单元格之间的范围才能合并它们。

使用类似这样的东西。

Option Explicit
Sub MergeCells()

Application.DisplayAlerts = False

Dim rng As Range
Dim LastColumn As Long
Dim ColumnsInRange As Long
Dim r As Long
Dim c As Long

'Last Column Used
LastColumn = ThisWorkbook.Sheets("Sheet1").Cells(3, Columns.Count).End(xlToLeft).Column

'Rows
For r = 3 To 4

'Columns
For c = 1 To LastColumn

Do While ThisWorkbook.Sheets("Sheet1").Cells(r, c) = ThisWorkbook.Sheets("Sheet1").Cells(r, c + 1)
ColumnsInRange = ColumnsInRange + 1
c = c + 1
Loop

Set rng = Range(Cells(r, c - ColumnsInRange), Cells(r, c))
rng.Select
With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge

    ColumnsInRange = 0

Next c

Next r

    Application.DisplayAlerts = True

End Sub