Excel使用VBA合并单列、多列单元格
多列合并相同内容单元格
合并相同单元格的功能如下同,让相同内容的单元格合并为一个。
具体代码如下:
Sub 相同内容合并单元格()
'
'
'
'
Dim i, j As Long
Dim allAddress As Variant
Dim mergeRange As Range
Set mergeRange = Selection
allAddress = Split(mergeRange.Address, ",")
Application.DisplayAlerts = False
For j = 0 To UBound(allAddress)
'对每个所选区域的每列进行合并
Dim firstRow As Long
Dim firstColumn As Long
Dim seRange As Range
Dim columnsCount As Long
Dim k As Long
Set seRange = Range(allAddress(j))
firstRow = seRange.Row
firstColumn = seRange.Column
'循环每列
For i = firstColumn To firstColumn + seRange.Columns.Count - 1
'循环每行
For k = firstRow + seRange.Rows.Count - 1 To firstRow Step -1
If Cells(k, i) <> "" And k - 1 > 0 Then
If Cells(k, i).Value = Cells(k - 1, i).Value Then
Range(Cells(k, i), Cells(k - 1, i)).Merge
End If
End If
Next k
Next i
Next j
Application.DisplayAlerts = True
End Sub
选择区域,然后执行就可以合并多列的中相同内容的单元格,效果如下
上述VBA实现的功能,仅合并相同内容单元格,和WPS中的功能类似。
目前的不足在于,假如合并B列的单元格时,要求对应行A列单元格也一致,暂时无法满足,需进一步拓展,如下图:在VBA执行后,A、B列都有合并相同单元格,但B列性别合并后,没有与A列相同。即A列中(A2:A4合并后)B列对应的B2:B4也应该合并,但是代码只会合并B2:B6(都为女),无法一致.使用时需注意!