简体   繁体   中英

Excel vba hide rows until value

I want to hide rows 7 through X in Excel, where X is the row 6 rows above the first instance of a value in column A.

Google seems to come up with things that look WAY WAY too complicated for my purposes.

What I have so far is a basic:

'Select Rows 7 through 3 rows before the first instance of any text in column A, then hides them
Rows("7:62").Select
' have to update the 62 above to look for text and hide based on that
Selection.Rows.Group
Selection.EntireRow.Hidden = True

within my Sub. I just need to figure out how to change the 62 to be a variable cell that is usually around the 60's, but is not always the exact value of 62.

Try to avoid using Select when possible.

strValueToFind = "What ever the value you are trying to find in column A is"
With Sheets("Sheet1")
    'Find the row containing the value
    intFoundRow = .Range("A:A").Find(What:= strValueToFind, _
        LookIn:=xlValues, _
        LookAt:=xlWhole).Row
    'Now hide Rows 7 through 6 above the row we found
    .Rows("7:" & intFoundRow - 6).Hidden = True
End With

Hopefully that's not too complicated. :)

Your narrative says 'row 6 rows above' and your code says '3 rows before' . I usually believe the code. This is important due to the maths involved and ensuring that you are not trying to hide rows above row 7.

Dim rw As Variant
rw = Application.Match(Chr(42), Range("A8:A1048576"), 0)
If Not IsError(rw) Then
    rw = Application.Max(rw + 4, 7)
    Range("A7:A" & rw).EntireRow.Hidden = True
End If

Say we start with:

在此处输入图片说明

and we want to hide all rows 7 through 6 rows above the first occurrence of "happiness". Running this:

Sub FindAndHide()
    Dim rng As Range

    Set rng = Range("A:A")
    Range(Cells(7, 1), rng.Find(What:="happiness", after:=rng(7)).Offset(-6, 0)).EntireRow.Hidden = True
End Sub

will produce:

在此处输入图片说明

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