当单元格值= 0时隐藏相应的行

时间:2012-06-08 11:31:07

标签: excel-vba vba excel

当E列中的单元格值等于0(零)时,我试图自动隐藏/取消隐藏相应的行。这些单元格中有公式,当另一个单元格中的单元格发生变化时,这些公式会返回零。在那次改变后,我希望代码能够执行隐藏/取消隐藏魔法。

非常感谢。

2 个答案:

答案 0 :(得分:1)

这是使用AutoFilter的更快的方法。您可以直接调用此代码或在Worksheet_Calculate事件中使用它。我假设单元格E1有标题。

按钮

Option Explicit

Sub Sample()
    Dim rRange  As Range, RngToHide As Range
    Dim lRow As Long

    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False

    With Sheets("Sheet1")
        lRow = .Range("E" & Rows.Count).End(xlUp).Row
        Set rRange = .Range("E1:E" & lRow)

        With rRange
          .AutoFilter Field:=1, Criteria1:="0"
          Set RngToHide = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With
    End With

    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False

    If Not RngToHide Is Nothing Then RngToHide.Hidden = True
End Sub

工作表计算事件 - 不推荐

我不建议自动调用此代码,因为如果您想要更改隐藏行中的某些内容,则不会取消隐藏行。要取消隐藏行,您必须在Worksheet_Calculate事件中注释掉整个代码,或者在连接的单元格中将值更改为非零值(提供连接的单元格不在隐藏的行中)。

当Col E中的值更改为0

时,这将隐藏行
Option Explicit

Private Sub Worksheet_Calculate()
    Dim rRange  As Range, RngToHide As Range
    Dim lRow As Long

    On Error GoTo Whoa

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False

    With Sheets("Sheet1")
        lRow = .Range("E" & Rows.Count).End(xlUp).Row
        Set rRange = .Range("E1:E" & lRow)

        With rRange
          .AutoFilter Field:=1, Criteria1:="0"
          Set RngToHide = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With
    End With

    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False

    If Not RngToHide Is Nothing Then RngToHide.Hidden = True

LetsContinue:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

答案 1 :(得分:0)

使用这个mhetod:

Sub HideRows()
Dim i As Integer
i = 1
Do While Not Cells(i, 5) = ""
    If Cells(i, 5).Value = 0 Then
        Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = True
    ElseIf Cells(i, 5).Value <> 0 And Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = True Then
        Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = False
    End If
i = i + 1
Loop
End Sub

您可以添加按钮并通过Button_Click事件调用此方法,或者将下一个方法添加到 Microsoft Excel对象中的必要工作表

Private Sub Worksheet_Change()
    Module1.HideRows
End Sub 

当某些单元格发生变化时,此方法将调用HideRow方法。