Hiding Rows Based on Cell Dropdown with VBA

MeganMorris-3621 0 Reputation points
2024-01-19T15:15:26.5033333+00:00

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. User's image Thank you in advance, Megan

Microsoft 365 and Office | Development | Other
Microsoft 365 and Office | Excel | For business | Windows
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.