简体   繁体   中英

Excel, VBA, show() hide() rows

I am trying to hide/show a range of rows based on the contents of a cell. Using the code below, but I keep getting the #name error

Function HURows(ByVal rng As Range)
    If rng.Value = "TRUE" Then
        Range("C8:L23").Hidden = True
        Str = "Hidden"
    Else
        Range("C8:L23").Hidden = False
        Str = "Shown"
    End If

    HURows = Str
End Function

This code has been placed in the section for Sheet1 (Sheet1) VBA code, and is being used in Sheet1 =HURows(C3) .

You have at least two problems:

  1. a UDF can only return a value and not hide/unhide rows
  2. Hidden should be applied to an entire row not just a block of cells

    There may be other problems

As Gary says the Function can only show a value, you will ned a macro to hide and unhide rows.

We can use a worksheet event to get the code to work automatically, you would have to supply more details though. In the meantime, here is a bit of code to get you started.

Sub HideRws()
    Dim HidRw As Range, x, s As String
    Dim rng As Range
    Set rng = Range("A1")
    Set HidRw = Range("C8:L23")
    HidRw.EntireRow.Hidden = False
    x = IIf(rng = "True", 1, 0)
    s = IIf(rng = "True", "Hidden", "Shown")

    HidRw.EntireRow.Hidden = x
    rng.Offset(0, 1) = s

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM