加快VBA执行速度

时间:2016-10-31 21:41:44

标签: performance excel-vba macros excel-2013 vba

所以我有以下VBA宏设置,当CompHide运行时需要几分钟才能更新。我觉得这是因为C.EntireRow.Columns(43).Value =""

我尝试制作一个新的帮助"将检查两列是否为空并且返回" Y"或" N"然后让宏看看那个" Y"并隐藏那些。这加速了一些,但如果可能的话,我想要更快。

原始代码:

Sub CompHide()

    Dim sht As Worksheet, C As Range

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set sht = Sheets("Comparison")
        sht.Rows.Hidden = False

    CSetRowVis "C9", "CMarket1"
    CSetRowVis "C115", "CMarket2"
    CSetRowVis "C221", "CMarket3"
    CSetRowVis "C329", "CMarket4"
    CSetRowVis "C437", "CMarket5"
    CSetRowVis "C545", "CMarket6"
    CSetRowVis "C653", "CMarket7"
    CSetRowVis "C761", "CMarket8"
    CSetRowVis "C869", "CMarket9"
    CSetRowVis "C977", "CMarket10"

    For Each C In sht.Range("CNonTest")
        If C.Value = "" And C.EntireRow.Columns(43).Value = "" Then
            C.EntireRow.Hidden = True
        End If
    Next

    sht.Range("CBlank").EntireRow.Hidden = True

    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

Sub CSetRowVis(addr As String, rngName As String)
    With Sheets("Comparison")
        If .Range(addr).Value = "Unused" Then
            .Range(rngName).EntireRow.Hidden = True
        End If
    End With
End Sub

新守则:

Sub CompHide()

    Dim sht As Worksheet, C As Range

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set sht = Sheets("Comparison")
        sht.Rows.Hidden = False

    CSetRowVis "C9", "CMarket1"
    CSetRowVis "C115", "CMarket2"
    CSetRowVis "C221", "CMarket3"
    CSetRowVis "C329", "CMarket4"
    CSetRowVis "C437", "CMarket5"
    CSetRowVis "C545", "CMarket6"
    CSetRowVis "C653", "CMarket7"
    CSetRowVis "C761", "CMarket8"
    CSetRowVis "C869", "CMarket9"
    CSetRowVis "C977", "CMarket10"

    For Each C In sht.Range("CHideTest")
        If C.Value = "Y" Then
            C.EntireRow.Hidden = True
        End If
    Next

    sht.Range("CBlank").EntireRow.Hidden = True

    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

Sub CSetRowVis(addr As String, rngName As String)
    With Sheets("Comparison")
        If .Range(addr).Value = "Unused" Then
            .Range(rngName).EntireRow.Hidden = True
        End If
    End With
End Sub

这是使用Excel 2013 Standard 64位。行数刚好低于1200.列数为150.所有这些单元格都是公式

如果您需要任何额外信息,请告知我们。

1 个答案:

答案 0 :(得分:2)

而不是:

For Each C In sht.Range("CHideTest")
    If C.Value = "Y" Then
        C.EntireRow.Hidden = True
    End If
Next

考虑这样的事情:

Dim rng As Range 'for collecting rows to be hidden

For Each C In sht.Range("CHideTest")
    If C.Value = "Y" Then
        if rng Is Nothing Then
            set rng = C
        Else
            set rng = application.union(rng, C)
        end if
    End If
Next

'hide all accumulated rows (if any found)
if not rng is nothing then rng.EntireRow.Hidden = True