I am attempting to write an Excel macro to change the color of at textbox automatically based on an input value from a cell in the sheet. The code that I currently have is:
Private Sub TextBox1_Change()
'Declare Variables
Dim cell As Range
Dim color As String
'Initialize Variables
Set cell = Range("A1")
color = cell.Value
'Set TextBox Color
If color = "" Then TextBox1.BackColor = RGB(255, 255, 255) 'white
If color = "1" Then TextBox1.BackColor = RGB(255, 0, 0) 'red
If color = "2" Then TextBox1.BackColor = RGB(0, 255, 0) 'green
If color = "3" Then TextBox1.BackColor = RGB(0, 0, 255) 'blue
End Sub
This is supposed to read a value from cell A1, then change the color of the textbox based on that value. My code does successfully change the color of the textbox, but it doesn’t update until after I click into the textbox and type something. Is there a way to make the color update as soon as a value is entered into cell A1?
If it would be easier to do this with some other object I am not tied to a textbox but cannot just use a cell.
As @findwindow suggested, you could use the Worksheet_Change
event instead of the text-box event:
Private Sub Worksheet_Change(ByVal Target As Range)
'Declare Variables
Dim cell As Range
Dim color As String
If Target.Address = Range("A1").Address Then
'Initialize Variables
Set cell = Range("A1")
color = cell.Value
'Set TextBox Color
If color = "" Then TextBox1.BackColor = RGB(255, 255, 255) 'white
If color = "1" Then TextBox1.BackColor = RGB(255, 0, 0) 'red
If color = "2" Then TextBox1.BackColor = RGB(0, 255, 0) 'green
If color = "3" Then TextBox1.BackColor = RGB(0, 0, 255) 'blue
End If
End Sub
Tags: excelexcel, text, vba