Excel宏更改文本框颜色

时间:2016-05-25 15:28:02

标签: excel vba excel-vba

我正在尝试编写Excel宏来根据工作表中单元格的输入值自动更改文本框的颜色。我目前拥有的代码是:

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

这应该从单元格A1读取值,然后根据该值更改文本框的颜色。我的代码确实成功地更改了文本框的颜色,但直到我单击文本框并键入内容后才会更新。一旦将值输入单元格A1,有没有办法使颜色更新?

如果使用其他对象更容易做到这一点,我不会被绑定到文本框但不能只使用单元格。

1 个答案:

答案 0 :(得分:2)

正如@findwindow建议的那样,您可以使用Worksheet_Change事件而不是文本框事件:

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