根据列表值隐藏/取消隐藏某些行

时间:2018-10-04 19:47:27

标签: vba excel-vba hide

我试图根据列表值隐藏/取消隐藏某些行,如果它们被隐藏,请将单元格设置为0。如果我选​​择1,则代码将隐藏行,但是如果我选择其他任何行,则不会取消隐藏它们值。我可用的值是1到5。

Private Sub Worksheet_Change(ByVal Target As Range)
    'Updated by Extendoffice 20180822
    If Target.Address = "$F$16" Then
        If Target.Value <= 2 Then
            Application.Rows("22:25").Select
            Application.Selection.EntireRow.Hidden = True
            Range("F22").Value = "0"
            Range("F23").Value = "0"
            Range("F24").Value = "0"
            Range("F25").Value = "0"
        ElseIf Target.Value <= 3 Then
            Application.Rows("23:25").Select
            Application.Selection.EntireRow.Hidden = True
            Range("F23").Value = "0"
            Range("F24").Value = "0"
            Range("F25").Value = "0"
        ElseIf Target.Value <= 4 Then
            Application.Rows("24:25").Select
            Application.Selection.EntireRow.Hidden = True
            Range("F24").Value = "0"
            Range("F25").Value = "0"
        ElseIf Target.Value <= 5 Then
            Application.Rows("25:25").Select
            Application.Selection.EntireRow.Hidden = True
            Range("F25").Value = "0"
        ElseIf Target.Value <= 6 Then
            Application.Rows("22:25").Select
            Application.Selection.EntireRow.Hidden = False
        End If
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

通过选择1,您将看到第一个IF语句并隐藏22:25。通过尝试更改值,将不会执行任何操作,因为“ ElseIf Target.Value <= 6 Then”将永远不会执行,因为每个值均<=6。您需要在触发事件时“重置”您的值- >在If Thens ...之前将其添加到Sub的顶部。

If Target.Address = "$F$16" Then
        Application.Rows("22:25").Select
        Application.Selection.EntireRow.Hidden = False
        Range("F22").Value = "[whatever default value should be]"
        Range("F23").Value = "[whatever default value should be]"
        Range("F24").Value = "[whatever default value should be]"
        Range("F25").Value = "[whatever default value should be]"

答案 1 :(得分:0)

您的代码只说要在特定条件下隐藏行,除了在单元格= 6的情况下,它不会说要在其他情况下显示行,但是逻辑永远不会走那么远,因为1-5中的任何值都将满足前5个条件,然后退出if语句。

如果要来回翻转hidden布尔值(真/假值),则可以将布尔变量设置为不具有自身亮度,然后将hidden属性设置为该值:

Dim TorF as Boolean
TorF = Application.Selection.EntireRow.Hidden 'to set the boolean's value

Application.Selection.EntireRow.Hidden = Not TorF 'to flip it