问题
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:
I have 44 text boxes on a userform whose names all start with "ch" example "chTextBox1"
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