Hiding Rows Based on Cell Dropdown with VBA
Microsoft® Excel® for Microsoft 365 MSO (Version 2308 Build 16.0.16731.20370) 64-bit - Hide Rows Using VBA
I am looking to find a way to hide certain rows based on a drop-down answer, as shown below (i.e., if the dropdown answer is 3, only 3 rows will show). I don't want to hide the text, but the rows themselves.
Here's the code for a script I recorded of setting the dropdown to 10 and the last 5 rows of the chart hiding, so that only 10 rows show, except I don't want the script to set the value, I want the user to set the value and for the visibility to be set based on that value automatically:
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
// Set range B9 on selectedSheet
selectedSheet.getRange("B9").setValue("10");
// Set visibility of row(s) at range 21:25 on selectedSheet to true
selectedSheet.getRange("21:25").setRowHidden(true);
}
Here's the code for a script the AI suggested, which didn't work:
Sub HideRows()
Dim selectedSheet As Worksheet
Dim numRows As Integer
Dim i As Integer
Set selectedSheet = ActiveSheet
numRows = selectedSheet.Range("B9").Value 'get the value of the dropdown
'loop through the rows and set the visibility based on the dropdown value
For i = 11 To 25
If i <= numRows + 10 Then 'show the row if it's within the range of the dropdown value
selectedSheet.Rows(i).Hidden = False
Else 'hide the row if it's outside the range of the dropdown value
selectedSheet.Rows(i).Hidden = True
End If
Next i
End Sub
I thought maybe I could combine setting the visibility with either a conditional formatting script or an if...then...elseif script, but I'm struggling to put it together. Below is a picture of the chart I'm attempting to format. The # of Materials being a dropdown numbered 0-15 (cell B9) and the rows to be hidden or revealed being 11-25.
Thank you in advance,
Megan