VBA通过用户窗体中的文本框控件进行循环

时间:2018-08-08 15:20:00

标签: vba excel-vba excel-2013

我浏览了许多有关UserForm控件循环的文章,但是似乎无法调整我发现的代码以满足我的需要,并且需要一些帮助。

我要弄清楚的情况:

  1. 我在一个用户窗体上有44个文本框,其名称均以“ ch”开头,例如“ chTextBox1”

  2. 当用户窗体激活时,我需要遍历所有以“ ch”开头的文本框,并将这些文本框的背景色更改为基于单元格内部颜色的颜色

    < / li>

下面是我一直在处理的代码,我要么陷入无限循环要么得到

  

错误424

Private Sub UserForm_Activate()
    Dim wb As Workbook
    Dim wsRR As Worksheet
    Dim bColor As Range
    Dim c As Control
    Dim y As String

    Set wb = Application.ThisWorkbook
    Set wsRR = wb.Sheets("RiskRating")
    Set bColor = wsRR.Range("C3")   

    For Each c In JHKey.Controls
        If TypeName(c) = "TextBox" Then
            y = Left(c, 2)
        End If
        If y = "ch" Then
            c.BackColor = bColor.Interior.Color
        End If
    Next c
End Sub

1 个答案:

答案 0 :(得分:1)

尝试将“ ch”的If语句测试放入“ TextBox”的If语句测试中。另外,在检查控件名称时,应为控件指定Name属性,否则默认为Value属性。另外,顺便说一句,我建议用关键字Me代替JHKey,该关键字指的是用户窗体本身,而不管其名称如何。

Private Sub UserForm_Activate()
    Dim wb As Workbook
    Dim wsRR As Worksheet
    Dim bColor As Range
    Dim c As Control
    Dim y As String

    Set wb = Application.ThisWorkbook
    Set wsRR = wb.Sheets("RiskRating")
    Set bColor = wsRR.Range("C3")

    For Each c In Me.Controls
        If TypeName(c) = "TextBox" Then
            y = Left(c.Name, 2)
            If y = "ch" Then
                c.BackColor = bColor.Interior.Color
            End If
        End If
    Next c
End Sub