如果单元格等于下一个可见单元格则隐藏行

Hiding row if cell equals next visible cell

我正在尝试编写一个宏,如果单元格值等于该列中的下一个可见单元格并循环遍历整列,则隐藏该行。我读到 SpecialCells(xlCellTypeVisible) 最多只能处理 8192 个单元格,而我的电子表格有 15,000 行。

我试过类似的方法,但想将其限制为仅可见的单元格

Sub Test()
For i = 7 To 15258
    If Range("P" & i).Value = Range("P" & i + 1).Value Then
        Rows(i).Hidden = True
    End If
Next i
End Sub

我曾尝试寻找解决方案,但还没找到。

谢谢!

如果不能稍微优化一下,我会感到惊讶,但它会满足您的需要。

您可以按照代码本身中的注释来了解它在做什么,但简而言之,您正在使用 For...Next 语句循环遍历可见单元格。对于每个可见单元格,您将搜索下一个可见单元格,然后检查是否匹配。如果是,则将该单元格添加到一个特殊范围,该范围跟踪要在代码末尾隐藏的所有行,然后将其隐藏。

Sub Test()

    Dim ws As Worksheet, lookupRng As Range, rng As Range, lstRow As Long
    Set ws = ThisWorkbook.Worksheets(1)
    lstRow = 15258
    Set lookupRng = ws.Range("P7:P" & lstRow)

    Dim rngToHide As Range, i As Long
    For Each rng In lookupRng.SpecialCells(xlCellTypeVisible)
        Application.StatusBar = "Checking row " & rng.Row & " for matches."
        For i = rng.Row + 1 To lstRow                   'Loop through rows after rng
            If Not ws.Rows(i).Hidden Then               'Check if row is hidden
                If rng.Value = ws.Cells(i, "P") Then    'check if the non-hidden row matches
                    If rngToHide Is Nothing Then        'Add to special range to hide cells
                        Set rngToHide = ws.Cells(i, "P")
                    Else
                        Set rngToHide = Union(rngToHide, ws.Cells(i, "P"))
                    End If
                End If
                Exit For                                'Exit the second For statement
            End If
        Next i
    Next rng

    Application.StatusBar = "Hiding duplicate rows"
    If Not rngToHide Is Nothing Then rngToHide.EntireRow.Hidden = True
    Application.StatusBar = False

End Sub