Excel VBA hide/Unhide Rows

38 Views Asked by At

i would like to implement a formula to have rows hidden or unhidden dependent on the product type, From the research i have done so far i have gathered the solution to this will be VBA. I have next to no experience with this topic how ever.

' code edited into the question from the comments
Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
 If Target.Address = "$B$1" Then 
  If Range("B1").Value = "Please Select" Then 
   Rows([11:52]).EntireRow.Hidden = True 
  ElseIf Range("B1").Value = "Red" Then 
   Rows([11:31]).EntireRow.Hidden = False 
   Rows([32:52]).EntireRow.Hidden = True 
  ElseIf Range("B1").Value = "Blue" Then 
   Rows([11:31]).EntireRow.Hidden = True 
   Rows([32:52]).EntireRow.Hidden = False 
  End If 
 End If 
End Sub

For an oversimplification of document scope the input reference will be product colour (Cell A1) and selection will use data validation (Cell B1) to of 2 choices (Red, Blue).

Essentially i would the first 10 rows to always remain visible, rows 11-31 should be visible if B1 input is 'Red' and rows 32-52 visible if B1 input is Blue.

i have tried a couple examples i have found however they seem to be out of date or involve password protection which i do not intend to use unless required. The attached image is a quick sort of over view on the desired operation,

Simplified Sheet Example

1

There are 1 best solutions below

2
Mark S. On

Here is the basic syntax of how to hide rows, but you will likely need to adjust it for things like defining the sheet, and adding conditions on when to hide those first 10 rows.

Sub hiderows()

If ActiveSheet.Cells(2, 1) = "Red" Then
    ActiveSheet.Rows("11:31").EntireRow.Hidden = True
End If

If ActiveSheet.Cells(2, 1) = "Blue" Then
    ActiveSheet.Rows("32:53").EntireRow.Hidden = True
End If

End Sub

Adjusting what FunThomas had mentioned you could alternatively approach it like so. However, you may want to have a button to toggle hiding the top cells which you said will always be hidden but likely want to be able to quickly and easily unhide.

Sub HideRows()

ActiveSheet.Rows("11:31").EntireRow.Hidden = (ActiveSheet.Cells(2, 1) = "Red")

ActiveSheet.Rows("32:53").EntireRow.Hidden = (ActiveSheet.Cells(2, 1) = "Blue")

End Sub