vba - 隐藏行宏需要很长时间才能运行

标签 vba excel

有没有办法让这段代码运行得更快?我正在尝试隐藏多个工作表中空白的行。

Option Explicit

Private Sub HideRows_Click()

Dim ws As Worksheet, c As Range

    Application.ScreenUpdating = False
    On Error Resume Next

    For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
        Case "Sheet1", "Sheet2", "Sheet3"
        'sheets to exclude
            'do nothing

        Case Else 'hide rows on these sheets
            For Each c In ws.Range("AJ16:AJ153,AJ157:AJ292")
                c.EntireRow.Hidden = c.Value = 0
            Next c
        End Select
    Next ws

    Application.ScreenUpdating = True

End Sub

最佳答案

以下是对您的代码进行的一些更改,旨在加快速度:

  • 关闭计算、事件和状态栏
  • 首先对 AJ 中的所有值进行分组通过 Union() 没有值函数,然后调用 EntireRow.Hide在该组合范围内

  • 老实说,这是一个非常干净的代码!
    Option Explicit
    
    Private Sub HideRows_Click()
    
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .DisplayStatusBar = False
            .EnableEvents = False
        End With
    
        'On Error Resume Next
    
        Dim ws As Worksheet
        For Each ws In Worksheets
    
            Select Case ws.name
                Case "Sheet1", "Sheet2", "Sheet3" 'sheets to exclude
                    'do nothing
    
                Case Else 'hide rows on these sheets
                    Dim unioned As Range
                    Set unioned = Nothing
    
                    Dim c As Range
                    For Each c In ws.Range("AJ16:AJ153,AJ157:AJ292")
                        If Len(c.Value2) = 0 Then
                            If unioned Is Nothing Then
                                Set unioned = c
                            Else
                                Set unioned = Union(unioned, c)
                            End If
                        End If
                    Next c
    
                    unioned.EntireRow.Hidden = True
            End Select
    
        Next ws
    
        With Application
            .Calculation = xlCalculationAutomatic
            .ScreenUpdating = True
            .DisplayStatusBar = True
            .EnableEvents = True
        End With
    
    End Sub
    

    关于vba - 隐藏行宏需要很长时间才能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51789752/

    相关文章:

    VBA "This Command is not Available because no document is open"

    excel - 如何在 Microsoft 脚本控件中实现事件?

    forms - 使用 Z 顺序和位置在 MS Access 中组织打开的表单

    vba - 将附件添加到现有电子邮件

    excel - Powershell 从 Excel 列导入的日期和时间格式错误

    由 ADO(来自 VBA)创建的数据库在 MS Access 中打开后减小了文件大小。为什么?

    excel - VBA CDate(Now()) 导致类型不匹配

    excel - 在 VBA 中查找适用于 MS Access 和 MS Excel 的应用程序目录路径

    excel - VBA 中的 IIF 函数

    c# - 使用 XML 数据基于模板创建动态 Excel 文件