【发布时间】:2015-07-20 23:37:26
【问题描述】:
我需要遍历所有行(除了我的标题行)并合并同一列中具有相同值的所有单元格。在我这样做之前,我已经确定该列已排序。 所以我有一些这样的设置。
a b c d e
1 x x x x
2 x x x x
2 x x x x
2 x x x x
3 x x x x
3 x x x x
需要这个
a b c d e
1 x x x x
2 x x x x
x x x x
x x x x
3 x x x x
x x x x
通过我的代码,我实现了合并两个相等的单元格。相反,我需要合并所有相等的单元格。
Dim i As Long
For i = 2 To Range("A" & Rows.Count).End(xlUp).Row
If Cells(i, 1) <> "" Then
If Cells(i, 1) = Cells(i - 1, 1) Then
Range(Cells(i, 1), Cells(i - 1, 1)).Merge
End If
End If
Next i
【问题讨论】:
-
重要的是,代码只合并特定列的单元格,而不是工作表的所有列。
-
这应该可以解决问题...
Sub MergeColumnA() Dim i As Long Dim myLastRow As Long Application.DisplayAlerts = False myLastRow = Cells(Rows.Count, "A").End(xlUp).Row For i = myLastRow - 1 To 6 Step -1 If Cells(i + 1, 1) <> "" Then If Cells(i, 1) = Cells(i + 1, 1) Then Range(Cells(i, 1), Cells(i + 1, 1)).Merge End If Next i Application.DisplayAlerts = True End Sub