简体   繁体   中英

How do I change the background color of a text box based on the value in it in vba?

So I have 2 textboxes A and B which by a commandbutton click gets populated automatically.

How do I change the background color of the textboxes when the values in them change ( If a user changes the values in them manually) ?

Thanks a lot!

When you click on the CommandButton:

TextBox1.Backcolor = 'something (example: &H000000FF&)

If the content of the TextBox is changed, use:

Private Sub TextBox1_Change()
   'Change the color
   'Just an example:

   If TextBox1.Text = "Hello" then
      TextBox1.Backcolor = &H0000C000&
   Else 
      TextBox1.Backcolor = &H000000FF&
   End If

End Sub

The .0 thing:

Label1.Caption = Ineteger & ".0"

You really don't need to round or anything, because you have Integers.

Vinay, You would do that like this:

Private Sub TextBox1_Change()
   TextBox1.BackColor = RGB(255, 0, 0)
End Sub

You'll want to put that in the TextBox1 object (double clicking it will get you there). The color change will be triggered when the value of the text box is changed. If I've understudy your question correctly, this should solve your problem. If not, please let me know.

SUPPLEMENT : A breakdown of the code

Private Sub TextBox1_Change() is an event handler. The code inside will run whenever a particular event occurs. In this case, whenever the text inside the TextBox1 changes. TextBox1.BackColor = RGB(255, 0, 0)

TextBox1 is an object, in this case it is your first texbox which is by default named "TextBox1", but we could use any other object in your form, "TextBox2", "Button1" etc...

.BackColor is a property of TextBox1 (its Back Color). We could set the BackColor property to any valid color, but here I went with red.

RGB stands for Red Green Blue. In this case we set the back of the TextBox to a color equil to 255 (All Red), 0 (with no Green), and 0 (No Blue).

SUPPLEMENT 2 So, based on your last comment, you would be looking to do something like this:

Private Sub TextBox1_Change()
    If TextBox1.Text = "5" Then
        TextBox1.BackColor = RGB(255, 255, 255)
    ElseIf TextBox1.Text = "6" Or TextBox1.Text = "4" Or TextBox1.Text = "5.6" Then
        TextBox1.BackColor = RGB(255, 0, 0)
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM