如何提高此代码的效率,使其运行更快?

时间:2019-04-16 09:08:10

标签: excel vba rows show-hide

我试图隐藏行,以便仅显示某些零售商数据,由于报表的布局,该数据不可过滤。我首先取消隐藏所有行作为重置,然后手动隐藏与零售商无关的行,直到仅保留点击的零售商信息为止。

但是,这是执行此操作的缓慢方法,我需要一种可以理解的快速方法。没有过滤数据的标准。单击按钮上的零售商名称即可。

我的代码显示了手动执行此操作的缓慢方式。

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

代码工作正常,我只想假设一种方法使用一些变量,以便更快地运行。

1 个答案:

答案 0 :(得分:1)

另一种方式:

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