vba - Excel 宏更改文本框颜色

标签 vba excel

我正在尝试编写一个 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 中输入值后立即更新颜色?

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

最佳答案

正如 @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

关于vba - Excel 宏更改文本框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441586/

相关文章:

vba - 处理 HTMLSelectElement 时未设置对象变量或 block 变量

vba - 在 VBA (excel) 中循环行的最有效/最快的方法是什么?

java - 使用 Apache POI 将工作表附加到 Excel 文件 - 由 NullPointerException 引起的 POIXMLException

java - 无法从jsf页面将数据表导出到excel

vba - Round(0.005) 会给出错误的结果吗?

vba - 通过键引用集合集合中的对象

excel - 进入新的私有(private)子目录时生成的超链接消失

excel - VBA Excel WebBrowser如何在.Click之前从代码中重置ReadyState?

excel - 创建一个未保存的空白工作簿

excel - 根据单元格内的值过滤列