Reputation:
I have a table of items and quantities, where I want to hide rows when the quantity is 0. The macro works, but it takes too long to complete.
This is the code:
Sub Hide2ndFix()
'
' Hide2ndFix Macro
'
BeginRow = 414
EndRow = 475
ChkCol = 24
For RowCnt = BeginRow To EndRow
If Cells(RowCnt, ChkCol).Value = 0 Then
Cells(RowCnt, ChkCol).EntireRow.Hidden = True
End If
Next RowCnt
'
End Sub
Is there a more efficient way of getting the same result, of hiding rows 414-475 if the value in column X is 0?
Upvotes: 3
Views: 2645
Reputation: 3322
The common way to make any code (that does any changing to the workbook) faster is by disabling screen updating
and disabling events
and changing the calculation
mode to Manual
(there are other ways, but these 3 things have the biggest factor).
And the the other thing is by collecting all rows in one union range has a big factor in deleting and inserting rows because the time that is needed to delete one row is similar to the time for deleting the whole union range. For example if deleting one row needs 1 second then deleting 1000 rows will need 1000 seconds, but deleting a union range that contains 1000 rows only needs 1 second.
Try this code:
Sub Hide2ndFix()
'
' Hide2ndFix Macro
'
Dim RowCnt As Long, uRng As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
BeginRow = 414
EndRow = 475
ChkCol = 24
For RowCnt = BeginRow To EndRow
If Cells(RowCnt, ChkCol).Value = 0 Then
If uRng Is Nothing Then
Set uRng = Cells(RowCnt, ChkCol)
Else
Set uRng = Union(uRng, Cells(RowCnt, ChkCol))
End If
End If
Next RowCnt
'
If Not uRng Is Nothing Then uRng.EntireRow.Hidden = True
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
Upvotes: 3