没有看到您的工作簿时,很难知道肯定,但一般Excel在隐藏行时非常缓慢。在您的代码中,每行都隐藏一行,因此可能有超过1000个单独的“隐藏此行”命令到Excel。
隐藏“块”中的行要快得多。这个宏(我在很久以前就写过,因为我正在处理同样的问题)这样做,所以它应该快得多。在你的情况,你会这样称呼它:
Call hideRows(ActiveSheet, 4, 2059, 0, 2, 2)
还有会隐藏行除非在第2列的值等于零倒置的设置。你只需要在你的函数调用结尾添加“True”。
Sub hideRows(ws As Worksheet, startRow As Long, endRow As Long, valCrit As Variant, Optional startCol As Long = 1, Optional endCol As Long = 1, Optional invert As Boolean = False)
Dim loopCounter As Long
Dim rowCounter As Long
Dim colCounter As Long
Dim endConsRow As Long
Dim tempArr As Variant
Dim toAdd As Long
Dim toHide As String
Dim sameVal As Boolean
Dim consBool As Boolean
Dim tempBool As Boolean
Dim rowStr As String
Dim goAhead As Boolean
Dim i As Long
If startRow > endRow Then
toAdd = endRow - 1
Else
toAdd = startRow - 1
End If
tempArr = ws.Range(ws.Cells(startRow, startCol), ws.Cells(endRow, endCol)).Value
ws.Rows(startRow & ":" & endRow).Hidden = False
loopCounter = 1
For rowCounter = LBound(tempArr, 1) To UBound(tempArr, 1)
For colCounter = LBound(tempArr, 2) To UBound(tempArr, 2)
sameVal = False
goAhead = False
If IsNumeric(valCrit) Then
If tempArr(rowCounter, colCounter) = valCrit Then
sameVal = True
End If
Else
If tempArr(rowCounter, colCounter) Like valCrit Then
sameVal = True
End If
End If
If sameVal Then
If invert = True Then
loopCounter = loopCounter + 1
Exit For
End If
goAhead = True
ElseIf colCounter = UBound(tempArr, 2) Then
If invert = False Then
loopCounter = loopCounter + 1
Exit For
End If
goAhead = True
End If
If goAhead = True Then
endConsRow = rowCounter
consBool = True
Do Until consBool = False
tempBool = False
For i = LBound(tempArr, 2) To UBound(tempArr, 2)
sameVal = False
If endConsRow = UBound(tempArr, 1) Then
Exit For
ElseIf IsNumeric(valCrit) Then
If tempArr(endConsRow + 1, i) = valCrit Then
sameVal = True
End If
Else
If tempArr(endConsRow + 1, i) Like valCrit Then
sameVal = True
End If
End If
If sameVal Then
If invert = False Then
endConsRow = endConsRow + 1
tempBool = True
End If
Exit For
ElseIf i = UBound(tempArr, 2) Then
If invert = True Then
endConsRow = endConsRow + 1
tempBool = True
End If
End If
Next
If tempBool = False Then
consBool = False
End If
Loop
rowStr = loopCounter + toAdd & ":" & endConsRow + toAdd
If toHide = "" Then
toHide = rowStr
ElseIf Len(toHide & "," & rowStr) > 255 Then
ws.Range(toHide).EntireRow.Hidden = True
toHide = rowStr
Else
toHide = toHide & "," & rowStr
End If
loopCounter = loopCounter + 1 + (endConsRow - rowCounter)
rowCounter = endConsRow
Exit For
End If
Next
Next
If Not toHide = "" Then
ws.Range(toHide).EntireRow.Hidden = True
End If
End Sub
这是否加快速度? '行(RowCnt).Hidden = True' – jsotola
我刚刚试过你的代码。它花了不到1/2秒。在空白工作表上的新工作簿中进行试用。 – jsotola
我敢打赌你的工作表在每次改变时都会进行计算。关闭类似'Application.EnableEvents = False'的事件,然后在重新启用屏幕更新时重新打开它们。 – Tim