Home » excel » excel – Having trouble grouping Sets of Rows in a toggle.button code

excel – Having trouble grouping Sets of Rows in a toggle.button code

Posted by: admin May 14, 2020 Leave a comment

Questions:

‘Im attempting to have a toggle button hide groups of rows. In this instance, Rows 15 through 20, 22 through 25, 27 and finally 30 through 32.

The code I have so far (which works as intended) is this….

Private Sub ToggleButton5_Click()
Dim xAddress As String

  xAddress = ("15:20")
  If ToggleButton5.Value Then
    Application.ActiveSheet.Rows(xAddress).Hidden = True
    ToggleButton5.Caption = "Show Assets"
  Else
    Application.ActiveSheet.Rows(xAddress).Hidden = False
    ToggleButton5.Caption = "Hide Assets"
  End If

End Sub

However I can not seem to add multiple groups to this row. FOr insance I have tried

xAddress = (“15:20,22:25”)

xAddress = “15:20,22:25”

xAddress = (“15:20 And 22:25”)

and I’ve even tried individually

xAddress = (“15,16,17,18,19,20,22,23,24,25”)

This last line works somewhat but runs into errors if more than maybe 6 row numbers are cited (going from memory on past attempts)

Thank you in advance for any help.

enter image description here

How to&Answers:

If you need a “toggle”, then consider the implementation of a “radio-button-logic”. It is either on or off, thus if it is not Hidden it should be Hidden and vice versa. Usually it is 1 line only:

Sub ToggleRowsVisibility()

    With ThisWorkbook.Worksheets(1).Range("15:20,22:25")
        .EntireRow.Hidden = Not .EntireRow.Hidden
    End With

End Sub

In the case of the code, it can be outside the If condition:

Application.ActiveSheet.Rows(xAddress).Hidden = ToggleButton5.Value

Answer:

Use Range instead of Rows.

Application.ActiveSheet.Range(xAddress).Hidden = True

If you are using Range, make sure that the row reference is in the form row:row, e.g. 1:1, 2:2, 3:3 and not 1, 2, 3.

I generally steer clear of Rows. For example,

Debug.Print Rows("1,2,3").Address

returns

$123:$123

Not what you expect, right?