Hiding cells by using VBA

余生颓废 提交于 2019-12-11 14:43:47

问题


I am using the following code to hide the required cells in Excel VBA.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Cell   As Range
    Set Cell = Range("$F$26")
    If Not Application.Intersect(Cell, Range(Target.Address)) Is Nothing Then
        If Range("F26").Value < 2 Then
            Rows("39:61").EntireRow.Hidden = True
            ElseIf Range("F26").Value < 3 Then
            Rows("47:61").EntireRow.Hidden = True
            ElseIf Range("F26").Value < 4 Then
            Rows("55:61").EntireRow.Hidden = True
            Else: Rows("39:61").EntireRow.Hidden = False
        End If
    End If
End Sub

It works perfectly when I put values in the descending order (like 4, 3, 2, 1). But after putting 1, if I am plan to switch to 2 or 3 (but not 4). Then it doesn't show the cells in second and third panel group. But if I put 4, then it again shows all panel groups. I attached the screenshots below.


回答1:


You've got to re-evaluate subsequent calls with new values in Range("$F$26") from scratch; e.g. make everything visible and then decide what gets hidden.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Range("F26"), Range(Target.Address)) Is Nothing Then
        Application.ScreenUpdating = False
        Rows("39:61").EntireRow.Hidden = False
        Select Case Range("F26").Value
            Case Is < 2
                Rows("39:61").EntireRow.Hidden = True
            Case 2
                Rows("47:61").EntireRow.Hidden = True
            Case 3
                Rows("55:61").EntireRow.Hidden = True
        End Select
        Application.ScreenUpdating = True
    End If
End Sub

I've changed your condition evaluation to a Select Case statement and removed the Cell variable as unnnecessary.

I could not find any contingency for when Range("F26") was blank. Currently, that falls under the < 2 condition.



来源:https://stackoverflow.com/questions/36190183/hiding-cells-by-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!