Excel隐藏行公式

时间:2016-12-16 14:23:27

标签: excel vba

如果引用单元格中没有文本,我试图隐藏工作表中的所有行。我正在使用以下公式

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

当我运行它时它会无限期地运行,我必须在任务管理器中退出该程序。我认为这种情况正在发生,因为我最初没有定义c。我对此是否正确?

感谢您抽出宝贵时间作出回应!

1 个答案:

答案 0 :(得分:1)

首先,您可以缩短并加快代码速度,如下所示:

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

但如果你隐藏了同一行范围D4:F100单元格为空的所有行,那么你可以使用这段代码:

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

可以更简洁,如下所示:

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

唯一需要注意的是,如果没有符合该条件的行,则会返回错误

如果这是一个问题,那么只需在子

的顶部添加On Error Resume Next即可