我正在尝试编写一个宏来隐藏行,如果单元格值等于该列中的下一个可见单元格并循环遍历整个列。我已经读过,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
我曾尝试寻找解决方案,但尚未能找到解决方案。
谢谢!
答案 0 :(得分:1)
如果不能稍微优化一下,我会感到惊讶,但它可以满足您的需求。
您可以按照代码本身中的注释来了解它正在做什么,但简而言之,您正在使用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