Search code examples
excelvbaexcel-2013

Sheet behaving very slow with hidden rows


For some reason this shee is behaving very sluggish anytime the macro runs. This is becoming problematic as every time I try to change information on unhidden cells that are not part of the range, it still runs an update and takes nearly 5-10 seconds to complete.

What changes to the formula need to take place to midigate this problem?

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

Solution

  • Your logic appears sketchy and it is a little hard to tell what you are trying to do but your logical can be shortened and used to determine the boolean .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