Excel宏更改文本框颜色

3

我正尝试编写一个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单元格输入数值时立即更新颜色?

如果使用其他对象更容易实现,我不一定非要使用文本框,但不能仅仅使用单元格。


不绑定到文本框,那么如何为单元格设置条件格式? - findwindow
那会非常容易。不过,单元格是我无法使用的少数东西之一。它需要成为某种 Excel 对象(例如文本框、标签等)。 - drylkuch
也许可以使用“worksheet_change”事件? - findwindow
1个回答

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

你可能在我发表评论的时候正在写这个^^ - findwindow
@findwindow 那个想法对于有经验的 VBA 程序员来说相当自然,但你首先提出了这个想法。 - John Coleman
嗯,注释比回答要快 =P - findwindow
难道不可以简单地写成 If Target.Address = "$A$1" Thencolor = target.Value 吗?这样就可以省略 Dim cell As RangeSet cell = Range("A1") - user3598756
@drylkuch 如果这个解决了你的问题,请打勾。只有你可以这样做。 - findwindow
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接