VBA 循环访问用户窗体中的文本框控件

VBA Loop through textbox controls in userform

我浏览了很多关于循环访问用户窗体控件的帖子,但似乎无法调整我为自己的需要找到的代码,需要一些帮助。

我想弄清楚的场景:

  1. 我在一个用户表单上有 44 个文本框,它们的名称都以 "ch" 开头示例 "chTextBox1"

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

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

Error 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

尝试将 "ch" 的 If 语句测试放在 "TextBox" 的 If 语句测试中。此外,您应该在检查其名称时为控件指定名称 属性,否则它默认为其值 属性。另外,顺便说一句,我建议用关键字 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