Forum Discussion
BrianBrucker
Dec 29, 2023Copper Contributor
vba hide a row syntax
This is what I am trying to hide by selecting and deselecting box k box s is the start of rows to be hidden and u is the last row to be hidden. I don't know what the proper syntax is to achieve this...
djclements
Dec 29, 2023Bronze Contributor
BrianBrucker If I've understood you correctly, the "Populate this section" checkbox shown in your screenshot is linked to cell K19 and controls rows 20 through 28. There are 21 checkboxes in total on the spreadsheet, each linked to a different cell (K19, K30, K39, K44, etc.) and each controlling their corresponding sections (rows 20-28, 31-37, 40-42, 45-49, etc.). If so, the following code should do the trick:
Sub ShowHideSections()
'Map the checkbox cells and their corresponding rows in an array
Dim sections As String, data As Variant
sections = "K19,20:28;K30,31:37;K39,40:42;K44,45:49;K51,52:53;" & _
"K55,56:63;K65,66:76;K78,79:82;K84,85:90;K92,93:96;K98,99:101;" & _
"K103,104:110;K112,113:119;K121,122:126;K128,129:142;K144,146:147;" & _
"K149,150:152;K154,155:161;K163,164:169;K171,172:176;K178,179:181"
data = Split(sections, ";")
'Loop through each linked cell and show/hide their corresponding rows
Dim ws As Worksheet, i As Long, arr As Variant
Set ws = Application.ActiveSheet
Application.ScreenUpdating = False
For i = LBound(data) To UBound(data)
arr = Split(data(i), ",")
If ws.Range(arr(0)).Value Then
ws.Rows(arr(1)).Hidden = False
Else
ws.Rows(arr(1)).Hidden = True
End If
Next i
Application.ScreenUpdating = True
End Sub
The Split method is used to extract the corresponding cell and row references from the delimited string, then show/hide each section accordingly, which is faster than looping through each row in each section to show/hide them one at a time.