Add Conditional Formatting to a User Form Command Button

Denny57

Board Regular
Joined
Nov 23, 2015
Messages
185
Office Version
  1. 365
Platform
  1. Windows
I have a series of Command Buttons in a User Form each of which will get different sets of information and poplate fields in the same User Form. I am wondering if there is a way to apply Conditional Formatting to each button based on the value of a specific cell in another worksheet.
The command Buttons are from the Developer Tool Box which appears with the User Form ( not Active x)

(If the cell in sheet 2 has a value > 0 then there is information to be access, other wise not.

Generic Requirement

User Form = frmInformation
Command Button 1
If value cell B2 in "sheet 2" > 0 then Command Button 1 BackColor = RGB(0,255,0)
Else Backcolour = RGB(255,0,0)

Command Button 2
If value cell D2 in sheet 2 > 0 then Command Button 2 Backcolour = RGB(0,255,0)
Else Backcolour = RGB(255,0,0)

Repeated for up to 20 Command Buttons

I assume that in each case I would need to activate Sheet2
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
You cannot use true conditional formatting for anything but cells.

Is the content of B2 and D2 values or formulas?

You will have to write event handlers in Sheet 2 to monitor changes in those cells, and that code will update the color of the buttons in the UserForm. There are two issues:

1. If the cells contain values that the user types in, you can use the Worksheet_Change event. If they contain formulas, you will have to use the Worksheet_Calculate event and check those cells every time there any recalculation of the sheet. This could have a slight impact on your user experience depending on how often there are recalculations.

2. The UserForm will also have to have code to set the color of these buttons in the UserForm_Initialize event so it will show the correct colors each time the form is newly instantiated.

Repeated for up to 20 Command Buttons
Why do you say "up to"? Isn't there a definite number of buttons?
The code has to be written for each button and cell combination. If there is a pattern (like B2, D2, F2.... and Button1, Button2, Button3, etc.), it can be done with a loop. Otherwise you will have to have 20 cases. How are your buttons named, and what cells determine their colors?

I assume that in each case I would need to activate Sheet2
You should never activate a sheet to read data from it or write data to it in VBA.

I can help with actual code once you provide the above details.
 
Upvote 0
Hi,

Assuming all values are on same sheet & the naming convention for your buttons is “CommandButton1”, “CommandButton2” etc etc then maybe following will do what you want

Place code in your Userforms code page.

Rich (BB code):
Private Sub UserForm_Initialize()
    Dim rng As Range, cell As Range
    Dim i   As Long
   
    Set rng = ThisWorkbook.Worksheets("Sheet2").Range("B2,D2")
   
    For Each cell In rng.Cells
        i = i + 1
        Me.Controls("CommandButton" & i).BackColor = _
        IIf(Val(cell.Value) > 0, rgbLime, rgbRed)
    Next cell
   
End Sub

Add to the range addresses shown in BOLD as required but do ensure that they are in correct order to match required commandbutton.


If requirement is more complex than suggested idea then provide more information about your project - plenty here to assist you

I assume that in each case I would need to activate Sheet2

There is seldom a need to have a sheet active for code to run as intended.

Hope Helpful

Dave
 
Upvote 0
You cannot use true conditional formatting for anything but cells.

Is the content of B2 and D2 values or formulas?

You will have to write event handlers in Sheet 2 to monitor changes in those cells, and that code will update the color of the buttons in the UserForm. There are two issues:

1. If the cells contain values that the user types in, you can use the Worksheet_Change event. If they contain formulas, you will have to use the Worksheet_Calculate event and check those cells every time there any recalculation of the sheet. This could have a slight impact on your user experience depending on how often there are recalculations.

2. The UserForm will also have to have code to set the color of these buttons in the UserForm_Initialize event so it will show the correct colors each time the form is newly instantiated.


Why do you say "up to"? Isn't there a definite number of buttons?
The code has to be written for each button and cell combination. If there is a pattern (like B2, D2, F2.... and Button1, Button2, Button3, etc.), it can be done with a loop. Otherwise you will have to have 20 cases. How are your buttons named, and what cells determine their colors?


You should never activate a sheet to read data from it or write data to it in VBA.

I can help with actual code once you provide the above details.
So, as once being an analyst looking for solutions to client requirements, I perhaps have a different understanding / expectation of coding, as I only ever requested solutions from the software developers. I am now what might be known as a "Silver Surfer" who keeps seeking solutions to improbable requirements!!!

I have developed this project over a period of time and it is basically a way of calculating the current status, returns and potential returns of different betting combinations.

Whilst I expect that a progammer might look at the archiecture and formulas which my file uses might look "clunky" (it includes a number worksheets which reference each other) , I am happy that whilst not being a programmer, that these actually work very well.

As a further challenge (and to keep my brain active), I have considered the use of 2 User Forms in the workbook. The first I use to input and update selection and result information (completed and functioning perfectly) and the second I use to display individual bet combination information. This has separate Command Buttons for each bet combination o be displayed (and it is to these that I wish to apply conditional formatting).
I currently have a table on Sheet 1, which looks at the value of a cell in Sheet3 which has been dynamically assigned to a bet combination and which is used to set the Conditional Formatting in the table in Sheet 1. I now wish to apply similar formatting to the individual Command Buttons in the second User Form and remove the current table.

The command Buttons in the second User Form works as expected, however, I am hoping that I can apply conditional formatting to each Command Button, by way of a BackColor to indicate active bet combinations. ( I have considered using a single Command Button which looks up a bet combination in a comboBox / TextBox, but could not get this to work. Instead I added a Command Button for each Bet Combination, hence why there are 19 Command Buttons.

From your response I have determined

1) The the lookup detail is a Value and will be different for each Command Button and is the resule of a VLOOKUP formula
2) Number of Command Buttons = 19

3) The code has to be written for each button and cell combination. = Yes

Each Command Button (there are 19) has a different cmdxxxxx name
Each Command Button looks at the formula result of a dynamically assigned cell in Sheet3, different for each bet combination, to determine
a) If the assigned cell value ="0" (Returns Conditional Formatting = BackColor RGB(255,0,0) {Red}
b) otherwise Conditional Formatting = BackColor RGB(0,255,0) {Green}

eg Bet Combination S1 lookup = Sheet3 Cell k2
eg Bet Combination D2 lookup = Sheet3 Cell H7

Sorry if this is little longwinded but hopefully this explains what I am hoping to, achieve.

Current code for the simplest Command Button ( only 1 selection) however, I would expect that a separate command Button to update all 19 Command Buttons might be a better option if not too long for VBA.

The idea of a" Refresh" Command Button seems the most appealing option.
I would just need the correct syntax

perhaps something along the lines of

VBA Code:
Private Sub cmd_Refresh
'Refreshes Active Bet Command Buttons

If (Sheets("Bet Selections").Range("K4").Value = 0 Then
cmdSingle1.BackColor = RGB(255, 0, 0) 'Red!
Else
cmdSingle2.BackColor = RGB(255, 255, 0) 'Green!

If (Sheets("BetSelections").Range("D16").Value = 0 Then
cmdSingle2.BackColor = RGB(255, 0, 0) 'Red!
Else
cmdSingle1.BackColor = RGB(255, 255, 0) 'Green!

End Sub

Hoping you can help
 
Upvote 0
Hi,

Assuming all values are on same sheet & the naming convention for your buttons is “CommandButton1”, “CommandButton2” etc etc then maybe following will do what you want

Place code in your Userforms code page.

Rich (BB code):
Private Sub UserForm_Initialize()
    Dim rng As Range, cell As Range
    Dim i   As Long
  
    Set rng = ThisWorkbook.Worksheets("Sheet2").Range("B2,D2")
  
    For Each cell In rng.Cells
        i = i + 1
        Me.Controls("CommandButton" & i).BackColor = _
        IIf(Val(cell.Value) > 0, rgbLime, rgbRed)
    Next cell
  
End Sub

Add to the range addresses shown in BOLD as required but do ensure that they are in correct order to match required commandbutton.


If requirement is more complex than suggested idea then provide more information about your project - plenty here to assist you



There is seldom a need to have a sheet active for code to run as intended.

Hope Helpful

Dave
Hi Dave

Sorry for the delay in responding

I needed to change the Command Button naming back to their original values and after changing your code to accomodate all 19 cells the code works only when the cell value is not equal to 0.

The problem I have determined is that the value of each cells is actually a VLOOKUP formula and the displayed detail is the result of the lookup. Thus each cell contains a formula even if the result is 0.

I tried changing

IIf(Val(cell.Value) > 0, rgbGreen, rgbRed)

to

IIf(Val(cell.Text) > 0, rgbGreen, rgbRed)

but this does not resolve the problem of the cells containing a formula.

Is there a change that can be made to your code to accept formula.

Example Formula . This is different for each cell

=VLOOKUP("S1A",Selections!$A$5:$AC$70,19,FALSE)

David
 
Upvote 0
Hi,
suggested idea only sets the commandbutton backcolor at time form is intialized (before it is displayed) & should work ok even with values derived from formula.

I created a temp sheet with VLookUp formula and got this result when form displayed

1653977552531.png


30-05-2022.xls
ABCDEF
1
20075
3
4
5
6
Sheet2
Cell Formulas
RangeFormula
B2B2=IF(ISNA(VLOOKUP(A7,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A7,Selections!$A$2:$C$5,3,FALSE))
D2D2=IF(ISNA(VLOOKUP(A8,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A8,Selections!$A$2:$C$5,3,FALSE))
F2F2=IF(ISNA(VLOOKUP(A9,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A9,Selections!$A$2:$C$5,3,FALSE))



Dave
 
Upvote 0
Hi,
suggested idea only sets the commandbutton backcolor at time form is intialized (before it is displayed) & should work ok even with values derived from formula.

I created a temp sheet with VLookUp formula and got this result when form displayed

View attachment 65939

30-05-2022.xls
ABCDEF
1
20075
3
4
5
6
Sheet2
Cell Formulas
RangeFormula
B2B2=IF(ISNA(VLOOKUP(A7,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A7,Selections!$A$2:$C$5,3,FALSE))
D2D2=IF(ISNA(VLOOKUP(A8,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A8,Selections!$A$2:$C$5,3,FALSE))
F2F2=IF(ISNA(VLOOKUP(A9,Selections!$A$2:$C$5,3,FALSE)),0,VLOOKUP(A9,Selections!$A$2:$C$5,3,FALSE))



Dave
Good Morning Dave

Just so as I have understood your solution, are you saying that I would need to change the VLOOKUP formula in each corresponding cell.

Example
In the example I provided, the code would need to be changed from =VLOOKUP("S1A",Selections!$A$5:$AC$70,19,FALSE) to
=IF(ISNA(VLOOKUP("S1A",Selections!$A$5:$AC$70,19,FALSE)),0,VLOOKUP("S1A",Selections!$A$5:$AC$70,19,FALSE))

I have tried this both with and without a value in the corresponding cell in the "Selections" worksheet but in both cases FALSE is returned. It no longer returns the value of the cell being looked up.

I have tried to understand what this is actually achieving as the cell will still contain a formula and not a value, which Conditional Formatting requires. Your previous solution requires the corresponding cell to have a value and not a formula.

I have a idea for a work around, however this would require the VALUE of the looked up cell (column 19) to be copied into a spare cell without the need for a formula. Is this possible?

Incidentally, the look-up value in Column A is not static as data is sorted and not fixed.


On a different matter, whilst I may be trying get VBA to manage some tasks which might best be handled differently, I was wondering if you might be able to suggest a good site or publication that clearly explains and provides examples of macros / coding for user forms and controls with VBA.
I am having difficulty finding clear and full examples of matters as simple as providing textbox details as numerics (and other formats) in the worksheets. It would be helpful if I could find a single source of information that clearly shows how User Form VBA should be coded to achieve many of the standard formatting that is available in Excel.

David
 
Upvote 0
Just so as I have understood your solution, are you saying that I would need to change the VLOOKUP formula in each corresponding cell.
Nothing to do with how the value in cell is derived.

This line in the code

VBA Code:
 Set rng = ThisWorkbook.Worksheets("Sheet2").Range("B2,D2,F2")

determines the range (cells) the code works with

The For Next Loop steps through each cell in the range & if Value is > 0 then as in my example, the appropriate CommandButton backcolor will when userform displayed, be Green otherwise Red.

Rich (BB code):
  For Each cell In rng.Cells
        i = i + 1
        Me.Controls("CommandButton" & i).BackColor = IIf(Val(cell.Value) > 0, rgbLime, rgbRed)
    Next cell

Should understand the code only runs once before form is displayed & that there is no link between the cells & commandbuttons.

Dave
 
Upvote 0
Nothing to do with how the value in cell is derived.

This line in the code

VBA Code:
 Set rng = ThisWorkbook.Worksheets("Sheet2").Range("B2,D2,F2")

determines the range (cells) the code works with

The For Next Loop steps through each cell in the range & if Value is > 0 then as in my example, the appropriate CommandButton backcolor will when userform displayed, be Green otherwise Red.

Rich (BB code):
  For Each cell In rng.Cells
        i = i + 1
        Me.Controls("CommandButton" & i).BackColor = IIf(Val(cell.Value) > 0, rgbLime, rgbRed)
    Next cell

Should understand the code only runs once before form is displayed & that there is no link between the cells & commandbuttons.

Dave
Dave, sorry but I must be missing something here. I have added the following to the Private Sub UserForm_Initialize() module. I am also not expecting the formatting to change after the form has been opened.

Each of the cells in the range contain a VLOOKUP formula as per the example provided earlier. The lookup value (eg S1A) is different for each cell in the range.

Currently in testing only Cells T4, T15 & AL4 will have returned a value > 0 . These correspond to Command Buttons 8, 9 & 14, which if the code was working would be green and the remaining buttons should be red. Instead all the buttons are red.
If I change the colour order then all the buttons become green.
This makes me believe that the code is identifying that each of the cells in the range is not greater than 0.
As three cells are showing a value greater than 0 then maybe there is something else which is being misunderstood.

I have used 0 , however, the cells are empty if no corresponding value is found.
The looked up value is in currency format. Might this make a difference?

VBA Code:
Dim rng As Range, cell As Range
    Dim i   As Long
   
    Set rng = ThisWorkbook.Worksheets("Bet Selections").Range("B4,B11,B18,B26,K4,K15,K26,T4,T15,T26,AC4,AC15,AC26,AL4,AL15,AL26,AU4,AU15,AU26")
   
    For Each cell In rng.Cells
        i = i + 1
        Me.Controls("CommandButton" & i).BackColor = IIf(Val(cell.Value) > 0, rgbGreen, rgbRed)
    Next cell
      
    End Sub
 
Upvote 0
The looked up value is in currency format. Might this make a difference?
If the currency symbol is text then Val function will return 0
Try replacing it with CCur function & see if resolves the issue

Rich (BB code):
Me.Controls("CommandButton" & i).BackColor = IIf(CCur(cell.Value) > 0, rgbGreen, rgbRed)

Dave
 
Upvote 0

Forum statistics

Threads
1,215,425
Messages
6,124,826
Members
449,190
Latest member
rscraig11

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