我有一个代码,如果该行中的单元格为零(或为空),则检查每一行。如果行适用于该规则,则该行将被隐藏。如果不是它仍然可见。
代码完美无缺,但速度非常慢(每次运行都需要大约40秒才完成)..
我想知道是否有人能够理解为什么我的代码很慢(或者我可以使用的替代方法比我当前的代码更快)..
Sub hide()
' Macro hides all rows with position "zero" or "blank"
Dim wb As Workbook
Dim ws As Worksheet
Dim c As Range
Dim targetRange As Range
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet 1")
Set targetRange = ws.Range("I10:N800")
targetRange.EntireRow.Hidden = False
For Each c In targetRange.Rows
If (WorksheetFunction.CountIf(c, "<>0") - WorksheetFunction.CountIf(c, "") = 0) And (WorksheetFunction.CountA(c) - WorksheetFunction.Count(c) = 0) Then
c.EntireRow.Hidden = True
End If
Next c
End Sub
答案 0 :(得分:6)
代码中消耗操作的最多时间是,每次在工作表上执行操作时,如果您隐藏每一行(多次),请执行以下操作:
c.EntireRow.Hidden = True
为了节省时间,每次满足条件时,只需将范围c
添加到MergeRng
,最后(退出循环时),只需隐藏整行马上。
尝试以下代码:
Dim MergeRng As Range ' define range object
For Each c In targetRange.Rows
If (WorksheetFunction.CountIf(c, "<>0") - WorksheetFunction.CountIf(c, "") = 0) And (WorksheetFunction.CountA(c) - WorksheetFunction.Count(c) = 0) Then
If Not MergeRng Is Nothing Then
Set MergeRng = Application.Union(MergeRng, c)
Else
Set MergeRng = c
End If
End If
Next c
' hide the entire rows of the merged range at one time
MergeRng.EntireRow.Hidden = True