VBA-Excel. How can I handle hide/unhide rows based on Private Sub Worksheet_Change(ByVal Target As Range)?

Good morning to all,

I am a newbie in macros & VBA Excel. I wish to handle hide/unhide rows based on Private Sub Worksheet_Change(ByVal Target As Range). I have the following code event

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="avalon"
If Target.Column = 2 Then
Application.EnableEvents = False
Cells(Target.Row, 5).Value = Date + Time
Application.EnableEvents = True
End If
ActiveSheet.Protect Password:="avalon"
End Sub

The idea is to aggregate this event (hide/unhide rows) when I entry data from 'B4'to 'B21' (Sometimes they will be filled totally and sometimes partially. It does not matter). Maybe, clicking in 'B21'or another event using double click in certain cell to activate unhide rows from 22 to 36 for follow up fill those rows. I hope to be clear, if not let me know to try to clarify my need to discover the proper code based on events.

Thanks in advance. I promise to learn quickly.

enter image description here

Upvotes: 1

Views: 1254

Answers (1)

HMVBA
HMVBA

Reputation: 176

It seems that what you are trying to do is to automatically hide or show rows based on the selection.

You can show or hide rows by using the .hidden on a range object (using EntireRow). You just need some way of determining when to hide these rows. By using the selectionChange event, you can show or hide rows based on what rows are currently selected.

The following code, when put on a worksheet object, will help you.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Select Case Target.Row
    Case 21
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = False
    Case 22 To 36
        ActiveSheet.UsedRange.EntireRow.Hidden = False
    Case Else
        ActiveSheet.Range("B22:B36").EntireRow.Hidden = True
End Select
End Sub

You can create more cases and give the row numbers that, when selected, will hide or show other ranges.

I hope I understood your question correctly.

Upvotes: 1

Related Questions