Mac – How to create a macro to show/hide rows based on a dropdown list

macrosmicrosoft excelvba

Tried to follow some advice based on a previous post (VBA code to hide or unhide rows based on a cell value) to create a macro so that I can show/hide certain rows based on a dropdown list. I'm pretty close to having it, but at least 1 part of my formula isn't working. Here's what I'm using:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("D13").Value = "Unlimited" Then
         Rows("77").EntireRow.Hidden = True
    ElseIf Range("D13").Value = "Unlimited" Then
        Rows("78:82").EntireRow.Hidden = False
    End If
    If Range("D13").Value = "Limited" Then
        Rows("78:82").EntireRow.Hidden = True
    ElseIf Range("D13").Value = "Limited" Then
        Rows("77").EntireRow.Hidden = False
    End If
    If Range("D13").Value = "Select one" Then
        Rows("78:82").EntireRow.Hidden = False
    ElseIf Range("D13").Value = "Select one" Then
        Rows("77").EntireRow.Hidden = False
    End If
End Sub

With this formula, I'm looking to influences what rows are shown below the dropdown list selection based on what the user selects. Cell with dropdown list is D13. It has 3 possible values: Limited, unlimited & select one. Here's what Im aiming for:

  • Select one: all rows from 77-82 are visible
  • Limited: Row 77 is visible, rows 78-82 are hidden
  • Unlimited: Row 77 is hidden, rows 78-82 are visible

The code I have above seems to work somewhat inconsistently: not sure if the functions I've set for each dropdown are overlapping each other unexpectedly? Right now my functions are working as expected only when you change from select one –> limited/unlimited, but I can't get them to continue working if you subsequently change to another selection.

Any help anyone has would be very appreciated!! Currently tearing my hair out a bit over this haha. Thanks in advance 🙂

Best Answer

The first line in the code below handles the Worksheet_Change. It makes sure only one cell was changed and that the cell was D13.

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("D13")) Is Nothing Or Target.Cells.Count > 1 Then
        Exit Sub

    ElseIf Range("D13").Value = "Select One" Then
        Rows("77:82").EntireRow.Hidden = False

    ElseIf Range("D13").Value = "Limited" Then
        Rows("77").EntireRow.Hidden = False
        Rows("78:82").EntireRow.Hidden = True    

    ElseIf Range("D13").Value = "Unlimited" Then
        Rows("77").EntireRow.Hidden = True
        Rows("78:82").EntireRow.Hidden = False   

    End If

End Sub

Note that the code above must be copied into the Worksheet object for whatever Sheet your dropdown is on.

enter image description here

I hope this helps, and good luck.

Related Question