如何解决用于隐藏行的缓慢 VBA 循环
以下代码用于遍历一个范围内的所有行,并根据该单元格中的单元格值隐藏它们,以及隐藏它们。如果两个单元格值都 = "",则意图是隐藏整行。一切正常,但速度非常慢。任何关于更快的建议将不胜感激。
Sheets("Morning Report Export Sheet").Activate
For x = 10 To 108
If Cells(x,9).Value = "" Then
If Cells(x + 1,9).Value = "" Then
Cells(x,9).EntireRow.Hidden = True
End If
End If
Next
... 也尝试过以下,但同样慢...
If Cells(x,9).Value = "" And Cells(x + 1,9).Value = "" Then
解决方法
我写了两个版本,因为我很无聊。
这是@MathieuGuindon提到的数组方法
Sub HideRowsUsingArrays()
Dim x As Long,HideRows As Range
Dim StartRow As Long,EndRow As Long,Col As Long
'TARGET RANGE
Col = 9
StartRow = 10
EndRow = 108
'TARGET RANGE
Dim sh As Worksheet
Set sh = Sheets("Morning Report Export Sheet")
Dim vArr() As Variant
'Saving all values in the target range to an array
vArr = sh.Cells(StartRow,Col).Resize(EndRow).Value
'Looping through the array
For x = LBound(vArr) To UBound(vArr) - 1
'If val or next val is empty
If vArr(x) = "" And vArr(x + 1) = "" Then
'Add the corresponding row to HideRows range
'Union causes an error if HideRows is nothing,so the first iteration cant use Union
If HideRows Is Nothing Then
Set HideRows = sh.Rows(x + StartRow - 1).EntireRow
Else
Set HideRows = Union(HideRows,sh.Rows(x + StartRow - 1).EntireRow)
End If
End If
Next x
'Hide the gathered rows
If Not HideRows Is Nothing Then HideRows.EntireRow.Hidden = True
End Sub
这是@TimWilliams 链接的 Range 方法
Sub HideRowsUsingRanges()
Dim cell As Range,Col As Long
'TARGET RANGE
Col = 9
StartRow = 10
EndRow = 108
'TARGET RANGE
Dim sh As Worksheet
Set sh = Sheets("Morning Report Export Sheet")
Dim r As Range
'Saving the target range
set r = sh.Cells(StartRow,Col).Resize(EndRow)
'Looping through each cell of the range
For Each cell In r
'If val or next val is empty
If cell.Value = "" And cell.Offset(1).Value = "" Then
'Add the corresponding row to HideRows range
'Union causes an error if HideRows is nothing,so the first iteration cant use Union
If HideRows Is Nothing Then
Set HideRows = cell
Else
Set HideRows = Union(HideRows,cell)
End If
End If
Next cell
'Hide the gathered rows
If Not HideRows Is Nothing Then HideRows.EntireRow.Hidden = True
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。