用VBA写一段EXCEL重复项批量合并代码
时间: 2024-01-26 13:02:25 浏览: 215
以下是用 VBA 写的 Excel 重复项批量合并代码:
```
Sub MergeDuplicateCells()
Dim lastRow As Long
Dim lastColumn As Long
Dim cellValue As String
Dim i As Long
Dim j As Long
Dim k As Long
Dim isDuplicate As Boolean
lastRow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lastColumn = ActiveSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For i = 1 To lastRow
For j = 1 To lastColumn
cellValue = ActiveSheet.Cells(i, j).Value
If cellValue <> "" Then
For k = i + 1 To lastRow
If cellValue = ActiveSheet.Cells(k, j).Value Then
isDuplicate = True
Exit For
End If
Next k
If isDuplicate Then
mergeCell i, k - 1, j
isDuplicate = False
End If
End If
Next j
Next i
End Sub
Sub mergeCell(firstRow As Long, lastRow As Long, column As Long)
With ActiveSheet.Range(ActiveSheet.Cells(firstRow, column), ActiveSheet.Cells(lastRow, column))
.Merge
.HorizontalAlignment = xlCenter
End With
End Sub
```
该代码将遍历整个工作表,并查找具有相同值的单元格。如果找到重复项,则将它们合并为一个单元格。请注意,此代码仅合并具有相同值的单元格,而不考虑任何格式或其他属性。如果需要,您可以根据需要进行调整和修改。
阅读全文