Change colour to show which button was last clicked

fawnlemur

New Member
Joined
Dec 9, 2018
Messages
29
Hi

I've researched and I can' find what I want the code do:

I want a code that will change a button's colour when it's clicked, but when another button is clicked it would change that button's colour and reset the previous ones.

I'm not too sure if there is a way to do it without linking to a specific button as I've got too many button.

I have tried to do it but came out with nothing, so I don't have any decent example code.

Thank you very much for your help
 
For ActiveX CommandButtons:-
Create a Class Module and name the class "cbGoods"

Place this code in Class Module
Code:
Option Explicit
Public WithEvents Cgood As MSForms.CommandButton
Private Sub Cgood_Click()
Dim shp As OLEObject
For Each shp In ActiveSheet.OLEObjects
  If shp.Name = Cgood.Name Then
    shp.Object.BackColor = RGB(255, 0, 255)
   Else
     shp.Object.BackColor = RGB(153, 205, 205)
   End If
Next shp
End Sub

Place this code in the "ThisWorkbook" module
Code:
Option Explicit
Dim cGoodRay() As cbGoods
Private Sub Workbook_Open()
Dim oneControl As OLEObject
Dim pointer As Long
ReDim cGoodRay(1 To ActiveSheet.OLEObjects.Count)
For Each oneControl In ActiveSheet.OLEObjects
      If TypeName(oneControl.Object) = "CommandButton" Then
            pointer = pointer + 1
            Set cGoodRay(pointer) = New cbGoods
            Set cGoodRay(pointer).Cgood = oneControl.Object 
        End If
    Next oneControl
    ReDim Preserve cGoodRay(1 To pointer)
End Sub

Close and Reopen Workbook.
Buttons should now Change/ChangeBack colour of Button on selection
 
Last edited:
Upvote 0

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.

Forum statistics

Threads
1,223,900
Messages
6,175,276
Members
452,629
Latest member
SahilPolekar

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top