Search code examples
excelvbarowsshow-hide

How can I make this code more efficient so that it runs quicker?


I am attempting to hide rows so that only a certain retailers data is shown, the data is not filterable due to the layout of the report. I start by just unhiding all rows as a reset and then manually hide rows that aren't relevant to a retailer until only the clicked retailers info remains.

However this is a slow way of doing this, and I need a quicker way I can understand. There is no criteria to filter the data. Just the retailer name on a click button.

My code shows the manual slow way of doing this.

Sub SummaryRetailer1Only()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'Resets hidden rows by showing everything.
ActiveSheet.Rows("2:480").EntireRow.Hidden = False

'Hides all rows that don't show data for Retailer1.
ActiveSheet.Rows("18:21").EntireRow.Hidden = True
ActiveSheet.Rows("37:48").EntireRow.Hidden = True
ActiveSheet.Rows("54:57").EntireRow.Hidden = True
ActiveSheet.Rows("73:84").EntireRow.Hidden = True
ActiveSheet.Rows("88:129").EntireRow.Hidden = True
ActiveSheet.Rows("261:376").EntireRow.Hidden = True
ActiveSheet.Rows("390:393").EntireRow.Hidden = True
ActiveSheet.Rows("409:420").EntireRow.Hidden = True
ActiveSheet.Rows("424:427").EntireRow.Hidden = True
ActiveSheet.Rows("443:454").EntireRow.Hidden = True

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

The code works fine I just want a way that I assume uses some variables so that it runs quicker.


Solution

  • Another way:

    Option Explicit
    
    Sub SummaryRetailer1Only()
    
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
    
        With ThisWorkbook.Worksheets("Sheet1") '<- It s better to create a with statement with the sheet you want to use insead of activesheet
    
            'Resets hidden rows by showing everything.
            .Rows("2:480").EntireRow.Hidden = False
    
            'Hides all rows that don't show data for Retailer1.
            Union(.Rows("18:21"), .Rows("37:48"), .Rows("54:57"), .Rows("73:84"), .Rows("88:129"), .Rows("261:376"), _
                    .Rows("390:393"), .Rows("409:420"), .Rows("424:427"), .Rows("443:454")).EntireRow.Hidden = True
    
        End With
    
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    
    End Sub