【问题标题】:How to loop through checkboxes on dynamically created userform?如何遍历动态创建的用户表单上的复选框?
【发布时间】:2015-07-15 18:29:29
【问题描述】:

我正在尝试使用动态创建的用户表单,并根据选中的框将某些单元格变灰。

作为背景,这是针对注塑设备的。 QA 设置正在运行的型腔编号。此动态用户表单根据在工作表上输入的型腔编号创建复选框。

Option Explicit

Private Sub UserForm_Initialize()

Dim col         As Long
Dim row         As Long
Dim lcol        As Long
Dim i           As Long
Dim j           As Long
Dim chkBox      As MsForms.CheckBox
Dim l           As MsForms.Frame
Dim t           As MsForms.Label

Set l = Me.Controls.Add("Forms.Frame.1", "cavz", True)
    l.Caption = "BLOCKED CAVITIES"
    l.Height = 195
Set t = l.Controls.Add("Forms.Label.1", "mark")
    t.Caption = "Mark all cavities that are currently blocked:"
    t.Width = 175
    t.Top = 10

col = 2 'Set your column index here
row = 8
lcol = 17
j = 1

For i = col To lcol
Set chkBox = l.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
If Worksheets("QA").Cells(row, i).Value <> "" Then
    chkBox.Caption = Worksheets("QA").Cells(row, i).Value
ElseIf Worksheets("QA").Cells(row, i).Value = "" Then
    GoTo 10
End If
If i <= 9 Then
    'MsgBox "i = " & i
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
ElseIf i > 9 Then
    j = j + 1
    'MsgBox "j = " & j
    chkBox.Left = 100
    chkBox.Top = 5 + ((j - 1) * 20)
End If
10
Next i

End Sub

Private Sub CommandButton2_Click()
Unload Me
End Sub

Private Sub CommandButton1_Click()

Dim x As Control
Dim cavz As MsForms.Frame

For Each x In cavz.Controls
If x.Value = True Then
    If x.Value = Range("B8") Then
        Range("B8:B14").Select
        Selection.Interior.ColorIndex = 16
    End If
End If
Next x

End Sub

我开始做一件事,不知何故这就是我的代码变成的。这不是最整洁的代码,但我仍然认为自己是这方面的新手。另外,这是我第一次自己找不到答案,因此是我第一次寻求帮助。因此,任何帮助将不胜感激!

谢谢!

更新 这很棒!谢谢唐。但是,我确实有一个后续问题。也许我一直在努力解决这个问题太久了,但我想不出更有效的方法来做到这一点。这是我现在正在做的事情:

For i = 2 To 17
Set ctl = Controls.Item("CheckBox_" & i)
    If ctl = True Then
        If i = 2 Then
            Range(Cells(j, c), Cells(m, c)).Select
            Selection.Interior.ColorIndex = 16
            Range(Cells(k, c), Cells(m, c)).Select
            With Selection
                .Merge
                Cells(k, c) = "BLOCKED"
                .Orientation = 90
                .VerticalAlignment = xlCenter
                .HorizontalAlignment = xlCenter
            End With
        End If
Next i

如果 i = 1 到 17,我正在编写过程中,但我觉得有一种更有效的方法,我就是无法破解它。

【问题讨论】:

  • 我不明白你在跟进中要做什么。
  • 这将选择单元格并更改其颜色并添加文本“BLOCKED”,如果它们在用户窗体上被选为被阻止。我可以使用 16 个 if 语句,我只是好奇是否有更好/更有效的方法。
  • 我没有看到 if 语句的原因。找出每种情况下的变化,并使用循环设置每次 c、m、j 和 k 的增量值。

标签: excel vba for-loop checkbox userform


【解决方案1】:

按照创建它们的相同方式按名称循环它们。

Dim ctl As Control

For i = 2 To 17
    Set ctl = Controls.Item("CheckBox_" & i)    
Next 'i

另外,我会为 col、lcol 等的初始值创建模块级常量,并在两个例程中重用它们。

【讨论】:

  • 嗨,唐!谢谢你。我刚刚对我的原始问题添加了更新,并想看看您是否有任何建议。再次感谢!
猜你喜欢
  • 2020-03-21
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
相关资源
最近更新 更多