简体   繁体   中英

VBA code to hide/unhide multiple rows in another worksheet based on cell output from another worksheet

I want to use VBA code for the following: based on a cell output (either "TRUE" or "FALSE" in cell W20, which changes based on whether a user checks a box or not), I want rows to be hidden/unhidden on another worksheet called "Analysis" worksheet based on the code below. I right clicked the "Summary" tab where cell W20 and the checkbox are located -> view code -> wrote the code below, but it's not working. I am very new to VBA, please help, it would be very appreciated, thanks in advance

Sub Worksheet_Change(ByVal Target As Range)

Set Target = Range("$W$20")
If Target.Value = "FALSE" Then
    Sheets("Analysis").Rows("54:55").EntireRow.Hidden = True
Else
    Sheets("Analysis").Rows("54:55").EntireRow.Hidden = False
End If
If Target.Value = "FALSE" Then
    Sheets("Analysis").Rows("94:95").EntireRow.Hidden = True
Else
    Sheets("Analysis").Rows("94:95").EntireRow.Hidden = False
End If
If Target.Value = "FALSE" Then
    Sheets("Analysis").Rows("134:135").EntireRow.Hidden = True
Else
    Sheets("Analysis").Rows("134:135").EntireRow.Hidden = False
End If
End If
End Sub

Excel doesn't recognize the modification of a cell value caused by the manipulation of form controls. I assume this is because Excel links a form control to a value and applies the changes itself, therefore not considering it a user change in the spreadsheet.

In order to make your code work, you will have to move your code into a module as a click event of your form control. Click the Developer tab and then Visual Basic. Once Visual Basic is open, you will notice on the left pane that you have a list of your worksheets within a VBA Project bearing the name of your workbook and your macro is currently within one of them. Once you found it, delete the code of your macro. Then, right-click on the name of your workbook and then select Insert > Module...

On the coding pane, insert this modified code:

Sub NameOfYourFormControlCheckBox_Click()

Dim MyRange As Range
Set MyRange = Range("$W$20")

If MyRange = False Then
    Sheets("Analysis").Rows("54:55").EntireRow.Hidden = True
ElseIf MyRange = True Then
    Sheets("Analysis").Rows("54:55").EntireRow.Hidden = False
End If
End Sub

Make sure that the name of the sub is the name of your form control (checkbox) followed by an underscore and then "click".

Hope this helps!

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