隐藏行

时间:2017-04-12 16:14:57

标签: excel vba excel-2013

出于某种原因,只要宏运行,这个表现就非常缓慢。这变得有问题,因为每次我尝试更改不属于范围的非隐藏单元格的信息时,它仍会运行更新并需要将近5-10秒才能完成。

需要对公式进行哪些更改才能解决此问题?

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range


    For Each c In Range("A7:A98")
        If c.Value = 0 And c.Value = vbNullString Then
        c.EntireRow.Hidden = True
        End If
    Next c

    For Each c In Range("A7:A98")
        If c.Value <> 0 And c.Value <> vbNullString Then
        c.EntireRow.Hidden = False
        End If
    Next c

End Sub

2 个答案:

答案 0 :(得分:1)

这样的事情对你有用:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rCheck As Range
    Dim rCell As Range
    Dim rHide As Range
    Dim lCalc As XlCalculation

    Set rCheck = Me.Range("A7:A98")

    With Application
        lCalc = .Calculation
        .Calculation = xlCalculationManual
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    On Error GoTo CleanExit

    If Not Intersect(Target, rCheck) Is Nothing Then
        rCheck.EntireRow.Hidden = False
        For Each rCell In rCheck
            If rCell.Value = 0 And rCell.Value = vbNullString Then
                If rHide Is Nothing Then
                    Set rHide = rCell
                Else
                    Set rHide = Union(rHide, rCell)
                End If
            End If
        Next rCell
    End If

    If Not rHide Is Nothing Then rHide.EntireRow.Hidden = True

CleanExit:
    With Application
        .Calculation = lCalc
        .EnableEvents = True
        .ScreenUpdating = True
    End With

End Sub

答案 1 :(得分:0)

你的逻辑看似粗略,有点难以分辨你想要做什么,但你的逻辑可以缩短并用来确定布尔值.Hidden。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("A7:A98")) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim trgt As Range
        For Each trgt In Intersect(Target, Range("A7:A98"))
            trgt.EntireRow.Hidden = CBool(trgt.Value = vbNullString)
        Next trgt
    End If

safe_exit:
    Application.EnableEvents = True

End Sub