Hi All,
I am trying to create VBA code that will automatically hide rows in my spreadsheet depending on whether other reference cells are marked with a Yes or a No.
You select what items are included in the list (Flask, Toolkit, Cage, and Box). If you select Yes, this item is included in the list in cells B8:E11. If you select No, I would like the entire row for that item to be automatically hidden.
Example:
Flask: Yes
Toolkit: No
Cage: Yes
Box: Yes
In the above situation, row 9 on this spreadsheet should be automatically hidden, since that is the dedicated line for toolkits. With the help of GPT, I am currently working with the following code:
SHEET1 (Code):
Private Sub Worksheet_Change(ByVal Target As Range)
' Check if the change is in the C2:C5 range and if a single cell is edited
If Not Intersect(Target, Me.Range("C2:C5")) Is Nothing Then
' If only one cell is edited (avoiding range changes like bulk edits)
If Target.Cells.Count = 1 Then
' Call the AdjustRows macro when a change occurs in C2:C5
Application.EnableEvents = False ' Disable events to avoid infinite loop
Call AdjustRows
Application.EnableEvents = True ' Re-enable events
End If
End If
End Sub
MODULE (Code):
Sub AdjustRows()
Dim ws As Worksheet
Dim a As Variant
Dim r As Integer
Dim i As Integer
Set ws = ThisWorkbook.Sheets("Sheet1") ' Adjust the sheet name as necessary
a = Array("Flask", "Toolkit", "Cage", "Box") ' Items to check
' Loop through each item
For i = 0 To UBound(a)
' Check the corresponding "Yes" or "No" value in C2:C5
If ws.Range("C2:C5").Cells(i + 1).Value = "Yes" Then
' If "Yes", unhide the row in the results table
ws.Rows(8 + i).Hidden = False
Else
' If "No", hide the row in the results table
ws.Rows(8 + i).Hidden = True
End If
Next i
End Sub
So far, the macro works great, but I want this to happen automatically, which it currently does not. With the above code, selecting Yes or No changes nothing, unless I run the macro manually.
Also, I have used the Worksheet_Change function in a separate spreadsheet (also for automatically hiding rows) for a separate purpose, and it worked fine there, so I don't think that is the problem.
Anybody have any ideas as to how I can get this to work?
Bookmarks