Excelmacros更改文本框颜色

我正在尝试编写一个Excelmacros来自动更改文本框的颜色根据工作表中单元格的input值。 我现在的代码是:

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中读取值,然后根据该值更改文本框的颜色。 我的代码确实成功地改变了文本框的颜色,但是直到我点击文本框并键入内容后才会更新。 是否有一种方法来使颜色更新只要一个值input到单元格A1?

如果用一些其他的对象来做这件事情会更容易一些,我不会绑定到一个文本框,但不能只使用一个单元格。

正如@findwindowbuild议的那样,您可以使用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