简体   繁体   中英

Excel Hide Rows Formula

I'm trying to hide all rows in a worksheet if a reference cell has no text in it. I'm using the following formula

Option Explicit
Private Sub Worksheet_Activate()

Dim r As Range, c As Range
Set r = Range("d4:f1000")
Application.ScreenUpdating = False
For Each c In r
    If Len(c.Text) = 0 Then
    c.EntireRow.Hidden = True
Else
    c.EntireRow.Hidden = False
    End If
Next c
Application.ScreenUpdating = True
End Sub

When I run it it runs indefinitely, and I have to exit the program in Task Manager. I think this is happening because I haven't initially defined c. Am I correct about this?

Thank you for taking the time to respond!

first off you can shortened and speed up your code like follows:

Option Explicit
Private Sub Worksheet_Activate1()
    Dim r As Range, c As Range

    Set r = Range("d4:f1000")
    Application.ScreenUpdating = False
    For Each c In r
        c.EntireRow.Hidden = Len(c.Text) = 0
    Next c
    Application.ScreenUpdating = True
End Sub

but if you're after hiding all rows where range D4:F100 cells in the same row are blank, then you can use this code:

Private Sub Worksheet_Activate4()
    Application.ScreenUpdating = False
    With Range("D4:F1000") '<-- reference your range
        With .Columns(1).SpecialCells(xlCellTypeBlanks) '<--| reference its 1st column blank cells
            With .Offset(, 1).SpecialCells(xlCellTypeBlanks) '<--| reference referenced blank cells whose side cell is blank
                With .Offset(, 1).SpecialCells(xlCellTypeBlanks) '<--| reference referenced blank cells whose side cell is blank
                    .EntireRow.Hidden = True '<--| hide rows when all three cells are blank
                End With
            End With
        End With
    End With
    Application.ScreenUpdating = True
End Sub

which can be made much less verbose like follows:

Private Sub Worksheet_Activate5()
    Application.ScreenUpdating = False
    Range("D4:F1000") _
         .Columns(1).SpecialCells(xlCellTypeBlanks) _
         .Offset(, 1).SpecialCells(xlCellTypeBlanks) _
         .Offset(, 1).SpecialCells(xlCellTypeBlanks) _
         .EntireRow.Hidden = True '<--| hide rows when all three cells are blank
    Application.ScreenUpdating = True
End Sub

with the only caveat that should no rows match that criteria it'd return an error

should this be an issue then just add On Error Resume Next at the top of the sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM