Hide/Unhide toggle button which changes colour and text in vba

Arrow081974

New Member
Joined
Aug 4, 2018
Messages
3
Hello

I've been trying to write some VBA to set up a toggle button to hide multiple predefined columns.

I initially managed to define the code for the hide/unhide toggle and attached this to a shape

Sub togglecols()


Range("e:e,g:g").EntireColumn.Hidden = Not Range("e:e,g:g").EntireColumn.Hidden


End Sub
I then wanted a toggle button which would then change the colour of the button and text displayed on the button

Private Sub CommandButton1_Click()
With CommandButton1
If .BackColor = vbGreen Then
.BackColor = vbRed
.Caption = "Hidden"
.ForeColor = vbWhite
Else
.BackColor = vbGreen
.Caption = "Unhidden"
.ForeColor = vbBlack
End If
End With
End Sub
What I'm struggling with is combining these into a single piece of code that does both of these actions.

Broadly speaking what I want is
- when columns are hidden I want the toggle button to say "Hidden" and the toggle button to become red with white text
- when columns are not hidden I want the toggle button to say "Not Hidden" and the toggle button to become green with black text

Is anybody able to point me in the right direction? Thanks in advance
 

Some videos you may like

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.

mikerickson

MrExcel MVP
Joined
Jan 15, 2007
Messages
23,551
try
Code:
Sub togglecols()

    With Range("e:e,g:g").EntireColumn
        .Hidden = Not(.Hidden)
        if .Hidden then
            CommandButton1.Caption = "UnHide"
        Else
           CommandButton1.Caption = "Hide"
        End If
    End With
End Sub
 
Last edited:

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
40,626
Office Version
365
Platform
Windows
Another option
Code:
Private Sub CommandButton1_Click()
      Range("E:E,G:G").EntireColumn.Hidden = Not Range("E:E,G:G").EntireColumn.Hidden
      With CommandButton1
         .BackColor = IIf(.BackColor = vbRed, vbGreen, vbRed)
         .Caption = IIf(.Caption = "Hidden", "Unhidden", "Hidden")
         .ForeColor = IIf(.ForeColor = vbWhite, vbBlack, vbWhite)
   End With
End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,099,030
Messages
5,466,122
Members
406,468
Latest member
Toto Li

This Week's Hot Topics

Top