【发布时间】:2019-12-10 21:37:31
【问题描述】:
我正在尝试构建一个宏,它将遍历 Activeworkbook/Activeworksheet& Range("A1:" & LastColumn & LastRow) 并合并每列中的所有重复项。我能找到的最佳起点是这篇文章 --> fastest way to merge duplicate cells in without looping Excel
但是,就像@PEH 的答案 https://stackoverflow.com/a/45739951/5079799 上的 OP cmets 一样,我在 Set R = .Range(Join(arr, ",")) 线上收到以下错误 Application defined error。
是否有人有修复和/或更好/替代方法来合并列中的重复项?
答案代码:
Sub MergeCellsNew()
Application.DisplayAlerts = False
Dim n As Name
Dim fc As FormatCondition
Dim Rng As Range, R As Range
Dim lRow As Long
Dim I&, J&
Dim arr As Variant
ReDim arr(1 To 1) As Variant
With ThisWorkbook.Sheets("tst")
Set Rng = .Range("A2:D11")
lRow = Rng.End(xlDown).Row
For J = 1 To 4
I = 2 'I = Rng.Row to automatically start at the first row of Rng
Do While I <= lRow
Set R = .Cells(I, J) 'remember start cell
'run this loop as long as duplicates found next to the start cell
Do While Trim(UCase(.Cells(I, J))) = Trim(UCase(.Cells(I + 1, J)))
Set R = R.Resize(R.Rows.Count + 1) 'and resize R + 1
I = I + 1
Loop
'now if R is bigger than one cell there are duplicates we want to add to the arr
'this way single cells are not added to the arr
If R.Rows.Count > 1 Then
arr(UBound(arr)) = R.Address
ReDim Preserve arr(1 To UBound(arr) + 1)
End If
I = I + 1
Loop
Next J
ReDim Preserve arr(1 To UBound(arr) - 1)
Set R = .Range(Join(arr, ","))
With R
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Stop
End With
Application.DisplayAlerts = True
End Sub
【问题讨论】: