Home > OS >  Write macro on VBA to change colour of button
Write macro on VBA to change colour of button

Time:01-25

I've written a macro on VBA to change the colour of a button (lint). I want the button to be white, then green when clicked once, red when clicked again, and white when clicked again.

However, the code isn't working, and the button is just staying the original blue colour

Sub ChangeButtonColor()
Dim btn As Object


Set btn = ActiveSheet.Shapes("lint")


Select Case btn.Fill.ForeColor.RGB
    Case RGB(255, 255, 255)
        btn.Fill.ForeColor.RGB = RGB(0, 255, 0) 'green
    Case RGB(0, 255, 0)
        btn.Fill.ForeColor.RGB = RGB(255, 0, 0) 'red
    Case RGB(255, 0, 0)
        btn.Fill.ForeColor.RGB = RGB(255, 255, 255) 'white
End Select


End Sub

CodePudding user response:

Your code works for me, you just need to make sure that:

1. it actually runs when you press the button (right click on the "button" -> assign macro -> select changeButtonColor

2. your button is a shape added via insert -> shapes and not the form button from the developer tab (that one can't be colored)

3. The fill color of the button is preset to one of the three colors you specified in your code, white would be the easiest I guess.

  • Related