PDA

View Full Version : [SOLVED:] Switching 3 colors on Form



Malak
04-25-2023, 05:56 PM
Hello,
I wonder how the following code must be updated so the back color is:

1st click: yellow
2nd click: red
3rd click: blue
4th click: yellow
etc.


Sub btnMyButton_Click()
' The background color is gray at the beginnng
If frmMyForm.BackColor <> vbYellow Or frmMyForm.BackColor = vbRed Then
frmMyForm.BackColor = vbYellow
Else
frmMyForm.BackColor = vbRed
End If
End Sub

Thank you, Malak

June7
04-25-2023, 06:08 PM
Need to save this count somewhere and refer to that saved value. Options:

1. an unbound textbox

2. a public/global variable

3. TempVars

Be aware that VBA variables lose value in run-time errors, however, TempVars do not.

georgiboy
04-25-2023, 10:33 PM
Maybe the below will help:

Sub btnMyButton_Click()
' The background color is gray at the beginnng
Select Case frmMyForm.BackColor
Case -2147483633 ' grey (none)
frmMyForm.BackColor = vbYellow
Case 65535 ' yellow
frmMyForm.BackColor = vbRed
Case 255 ' red
frmMyForm.BackColor = vbBlue
Case 16711680 ' blue
frmMyForm.BackColor = vbYellow
End Select
End Sub

arnelgp
04-26-2023, 01:09 AM
you may also try:


Private Sub btnMyButton_Click()
Static iSwitch As Integer
Dim intValue As Integer
Dim lngColor As Long

iSwitch = iSwitch + 1

' there are only 3 for colors at the moment
intValue = (iSwitch Mod 3) + 1

'set the lngColor depending on intValue
lngColor = Choose(intValue, vbBlue, vbYellow, vbRed)

'The background color is gray at the beginnng
frmMyForm.BackColor = lngColor
End Sub

p45cal
04-26-2023, 02:53 AM
To deal with any number of colours, adjust the first line:

Private Sub btnMyButton_Click()
myColours = Array(vbYellow, vbRed, vbBlue, vbGreen, vbMagenta, 16737894, vbCyan) 'adjust this line to suit, this is an example.
'myColours = Array(vbYellow, vbRed, vbBlue) 'adjust this line to suit, this is the original request.
With frmMyForm
x = Application.Match(.BackColor, myColours, 0) 'is the current colour in the list? and if so, where?…
If IsError(x) Then 'no it isn't:
.BackColor = myColours(0) 'first colour in the list if it's not one of the existing colours.
Else 'yes it is:
.BackColor = myColours(x Mod (UBound(myColours) + 1)) 'the next colour in the list.
End If
End With
End Sub

Malak
04-26-2023, 07:27 PM
Thank you to everyone for providing your code. :yes

June7
04-26-2023, 10:54 PM
Oh, I get it now, colors are progressive so no need to track the click count. Duh!
Glad you have working solution.