VBA to show/hide rows based on whether a cell's value is zero

怎甘沉沦 提交于 2019-12-11 02:33:59

问题


I have an Excel sheet where I would like to hide or unhide certain rows depending on the value in another cell.

In Short:
The whole thing should depend on the value in cell C2, D2, E2.

If C2 is blank I would like rows 31 to 40 be hidden, if it is not blank, they need to be visible.

The same for the other three cells, always hiding/unhiding the following 10 rows:

D2 --> rows 41 to 50
E2 --> rows 51 to 60

I tried this code but it is not working and I do not get any error either:

Sub Hide_rows()
    If Range("LS!C2") = 0 Then
        Rows("31:40").EntireRow.Hidden = True
    Else
        If Range("LS!D2") = 0 Then
            Rows("41:50").EntireRow.Hidden = True
        Else
            If Range("LS!E2") = 0 Then
                Rows("51:60").EntireRow.Hidden = True
            Else
                If Range("LS!C2") > 0 Then
                    Rows("31:40").EntireRow.Hidden = False
                Else
                    If Range("LS!D2") > 0 Then
                        Rows("41:50").EntireRow.Hidden = False
                    Else
                        If Range("LS!E2") > 0 Then
                            Rows("51:60").EntireRow.Hidden = False
                        Else

                        End If
                    End If
                End If
            End If
        End If
    End If
End Sub

Thank you!


回答1:


Looks to me like you just need the following lines:

With Sheets("LS")
        .Rows("31:40").EntireRow.Hidden = (.Range("C2") = 0)
        .Rows("41:50").EntireRow.Hidden = (.Range("D2") = 0)
        .Rows("51:60").EntireRow.Hidden = (.Range("E2") = 0)
End With

EDIT as per Chris's point - the following will suffice:

With Sheets("LS")
        .Rows("31:40").Hidden = (.Range("C2") = 0)
        .Rows("41:50").Hidden = (.Range("D2") = 0)
        .Rows("51:60").Hidden = (.Range("E2") = 0)
End With



回答2:


Put this Worksheet_Change event driven sub procedure in the LS worksheet's private code sheet (right-clcik name tab, View Code), not in a public module code sheet.

sub worksheet_change(byval Target as range)
    if not intersect(target, range("C2:E2")) is nothing then
        on error goto safe_exit
        application.enableevents = false
        rows("31:40").entirerow.hidden = isempty(cells(2, "C"))
        rows("41:50").entirerow.hidden = isempty(cells(2, "D"))
        rows("51:60").entirerow.hidden = isempty(cells(2, "E"))
    end if
safe_exit:
    application.enableevents = true
end sub

Any change made to C2:E2 will trigger this sub procdure and the hidden/unhidden nature of those rows will be re-evaluated.



来源:https://stackoverflow.com/questions/51188828/vba-to-show-hide-rows-based-on-whether-a-cells-value-is-zero

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