0
votes

I have a button that will hide rows within a range if the cell has a specific color, I need it to toggle though back and forth hiding/unhiding the rows with each click. I don't know enough about VBA to fix it.

Sub hide_green()
    Dim Rng As Range
    Dim MyCell As Range
    Set Rng = Range("A11:A100")
    For Each MyCell In Rng
        If MyCell.Interior.ColorIndex = 43 Then
            MyCell.EntireRow.Hidden = True
        End If
    Next MyCell
End Sub

Also is it possible to change the text of the button each click to coordinate with "Hide" "Unhide"?

3
you can use filter by color - Rosetta
@Rosetta I do not know that a filter by color existed. I'm curious to know how to go about it. thx! - kaza
What version Excel do u use? if greater and equal 2007. you could filter by color without needing any VBA code, - ExcelinEfendisi
Filter by color only exists with newer versions of Excel. I believe it was added in 2007. - Liss

3 Answers

1
votes

Just add a second if to see if it's currently hidden or not.

Sub hide_green()
Dim Rng As Range
Dim MyCell As Range
Set Rng = Range("A11:A100")
For Each MyCell In Rng
    If MyCell.Interior.ColorIndex = 43 Then
        If MyCell.EntireRow.Hidden = True Then
            MyCell.EntireRow.Hidden = False
        Else
            MyCell.EntireRow.Hidden = True
        End If
    End If
Next MyCell
End Sub
1
votes

Liss has a good build on your code, though I would replace the If statements with a Select Case, just so it's cleaner.

For Each MyCell In Rng
    If MyCell.EntireRow.Hidden=True Then
        MyCell.EntireRow.Hidden=False
    Else
        Select Case MyCell.Interior.ColorIndex
        Case = 43
            MyCell.EntireRow.Hidden = True
        Case <> 43
            MyCell.EntireRow.Hidden = False
        End Select
    End If
Next MyCell
0
votes

Use this to quickly mark what color the rows are (on another column) enter image description here

Then just do filtering as usual

enter image description here

enter image description here