我如何加快循环

时间:2019-02-19 17:32:15

标签: excel vba performance loops

它运行得很好,但是执行速度比我想要的慢,我不确定为什么。我还有另一段代码也可以扭转这种情况...

只有5张纸循环通过,并且仅在给定范围内启动。它仅检查A列中的空值,如果为空,则行将隐藏。

我曾尝试关闭计算,事件和屏幕更新,但是它仍然不快……我是否在此某处缺少内存消耗???它的行为就像是要崩溃,但随后继续...

    Sub HideBlanks()
    Dim Sheet As Worksheet
    Dim r As Long

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    For Each Sheet In Worksheets
        If Sheet.Index > 1 Then
            With Sheet
                For r = 4 To 350
                    With activesheets
                        If Range("A" & r) = "" Then
                            Range("A" & r).EntireRow.Hidden = True
                        End If
                    End With
                Next r
            End With
        End If
        Range("a1").Select
    Next Sheet

    Worksheets(1).Activate

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

    End Sub

也许我完全是用错误的方式来做这件事...

最终目标是,如果值为“”,则隐藏(或防止)A4:G350之间的空白单元格打印这些行。

1 个答案:

答案 0 :(得分:3)

可以尝试

 Sub HideBlanks()
    Dim Ws As Worksheet
    Dim Rw As Long
    Dim Arr As Variant, Rng As Range

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    For Each Ws In ThisWorkbook.Worksheets
        If Ws.Index > 1 Then
        Arr = Ws.Range("A4:A350").Value
          For Rw = LBound(Arr) To UBound(Arr)
            If Arr(Rw, 1) = "" Then
                If Rng Is Nothing Then
                Set Rng = Ws.Range("A" & Rw + 3)
                Else
                Set Rng = Union(Rng, Ws.Range("A" & Rw + 3))
                End If
             End If
            Next Rw
        End If
   If Not Rng Is Nothing Then Rng.EntireRow.Hidden = True
   Set Rng = Nothing
   Next Ws

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

    End Sub