简体   繁体   中英

Hide and unhide rows by clicking on a cell above (loop)

I'm new to excel VBA and I'm trying out some code to learn on my own using internet.

I'd like to hide/unhide rows by clicking the cell right above the hidden cells. Let's say :

Cell D6 - Project title 1
Cell D7 - First row of Project1 contents
.
.
.
.
Cell D26 - Last row of Project1 contents
Cell D27 - Project title 2
Cell D28 - First row of Project2 contents
.
.
.
.
Cell D47 - Last row of Project2 contents

I want to be able to hide/unhide row 7 to 26 by clicking on cell D6. And click D27 to hide/unhide row 28 to 47. I have 50 projects titles and contents on the same sheet.

I tried using worksheet selection change but my code doesn't work. Can anyone show me how to do it ?

Thank you !

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim A As Range
Dim B As Range

B = A.Rows + 1 & ":" & A.Rows + 20

If A = Target.Address Then

    Rows(B).EntireRow.Hidden = Not Rows(B).EntireRow.Hidden

End If

Application.ScreenUpdating = True
End Sub

You'd need to refine a bit, but this single line will do the bulk of it.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Target.Offset(1).Resize(20).EntireRow.Hidden = Not Target.Offset(1).Resize(20).EntireRow.Hidden

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