Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide rows based on cell value

Tags:

excel

vba

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?


1 Answers

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
like image 196
Fadi Avatar answered Feb 06 '26 11:02

Fadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!