VBA Loop through textbox controls in userform

此生再无相见时 提交于 2020-07-10 08:46:09

问题


I have looked through numerous posts on looping through UserForm Controls but cant seem to adjust the code i have found for my needs and need some help.

Scenario I am trying to figure out:

  1. I have 44 text boxes on a userform whose names all start with "ch" example "chTextBox1"

  2. When the userform activates I need to loop through all of the text boxes that start with "ch" and change the background color of those textboxes to a color based on the interior color of a cell

Below is the code that I have been messing around with and I either end up in an infinite loop or I get

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

回答1:


Try placing the If statement testing for "ch" within the If statement testing for "TextBox". Also, you should specify the Name property for the control when checking for its name, otherwise it defaults to its Value property. Also, as an aside, I would suggest replacing JHKey with the keyword Me, which refers to the userform itself regardless of its name.

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


来源:https://stackoverflow.com/questions/51750281/vba-loop-through-textbox-controls-in-userform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!