如何合并行中重复的单元格值?我的代码忽略了一些重复值

How to merge duplicate cell values in rows? My code is ignoring some of the duplicate values

我正在尝试合并 D 列中所有连续的重复单元格。我不关心单元格的格式,也不需要对任何值求和。想知道我下面的代码有什么问题,因为并不是我所有的重复单元格都在合并......只能假设我不小心跳过了它们

with thisworkbook.sheets("sheet1") 
For i = StartRow + 1 To LastRow + 1
    
If Cells(i, 4) <> "" Then
    If Cells(i, 4) <> Cells(i - 1, 4) Then
        Application.DisplayAlerts = False
        Range(Cells(i - 2, 4), Cells(StartMerge, 4)).Merge
        Application.DisplayAlerts = True
        StartMerge = i
    End If
End If
Next i
End With

接近您的代码: (已更新;已删除 If Cells(i, 4) <> "" Then

Sub test1()
    With ThisWorkbook.Sheets("sheet1")
        StartRow = 1
        LastRow = .Cells(.Rows.Count, 4).End(xlUp).Row
        
        StartMerge = StartRow + 1
        Application.DisplayAlerts = False
        For i = StartRow + 1 To LastRow
            If .Cells(i, 4) <> .Cells(i + 1, 4) Then
                .Range(.Cells(StartMerge, 4), .Cells(i, 4)).Merge
                StartMerge = i + 1
            End If
        Next i
        Application.DisplayAlerts = True
    End With
End Sub

结果:

您可以使用枢轴 table 快速获得如下所示的视图。只是另一个没有编码的想法。仅供参考

索引、评估和过滤函数 避免循环遍历每个单元格的方法。使用这些函数,以下过程创建一个行号数组,其中单元格中的值与上述单元格值不匹配。

然后遍历数组以合并所需的“相同”单元格。

Sub MergeSameCells()
Dim ColRng As Range, RowArr
Application.DisplayAlerts = False
Set ColRng = Range("B2:B" & Range("B" & Rows.Count).End(xlUp).Row)

RowArr = Filter(Application.Transpose(Application.Index( _
            Evaluate("IF((" & ColRng.Address & "<>" & ColRng.Offset(1).Address & _
            "),ROW(" & ColRng.Address & "),""NA"")") _
            , 0, 1)), "NA", False, vbTextCompare)
Debug.Print UBound(RowArr)
'result 5, So there will be 6 loops (Zero based array) instead of 13.
For i = UBound(RowArr) To 0 Step -1
    If i = 0 Then
        If RowArr(i) - 1 <> 1 Then
        Range(Cells(2, "B"), Cells(RowArr(i), "B")).Merge
        End If
    Else
        If RowArr(i) - RowArr(i - 1) <> 1 Then
        Range(Cells(RowArr(i - 1) + 1, "B"), Cells(RowArr(i), "B")).Merge
        End If
    End If
Next i
Application.DisplayAlerts = True
End Sub