【问题标题】:Excel VBA: How to loop through checkboxes based on nameExcel VBA:如何根据名称循环复选框
【发布时间】:2016-12-23 18:58:53
【问题描述】:

我想使用 excel 和 vba 进行调查。我有一张桌子,上面有问题和答案。随着调查的开始,我的代码将通过覆盖表单上的复选框标签来列出答案。我将获取他们的答案并使用复选框的 True 或 False 值将它们写在一个列中。

变量“aRow”是每个问题的答案数。 “lastAns”是最后一个答案的行号。根据答案的数量,一些复选框将被隐藏,如图所示。 “CheckBox1”到“CheckBox4”是复选框的名称。

以下代码有效,但它太长了,我希望有一个更好的方法来循环检查复选框并每次更改它们的标签。请告诉我怎么做! 非常感谢!

     `lastAns = Cells(qRow, 5).End(xlDown).Row + 1
       aRow = lastAns - qRow
        If aRow >= 1 Then
            Me.CheckBox1.Visible = True
            Me.CheckBox1.Caption = Cells(qRow, 5)
            Else: Me.CheckBox1.Visible = False
        End If
        If aRow >= 2 Then
            Me.CheckBox2.Visible = True
            Me.CheckBox2.Caption = Cells(qRow + 1, 5)
            Else: Me.CheckBox2.Visible = False
            End If
        If aRow >= 3 Then
            Me.CheckBox3.Visible = True
            Me.CheckBox3.Caption = Cells(qRow + 2, 5)
            Else: Me.CheckBox3.Visible = False
            End If
        If aRow >= 4 Then
            Me.CheckBox4.Visible = True
            Me.CheckBox4.Caption = Cells(qRow + 3, 5)
            Else: Me.CheckBox4.Visible = False
            End If
               .....SAME CODE CONTINUES TILL 7...`

【问题讨论】:

  • 需要优化的工作代码应该发布在CodeReview。 AFAIK,您需要将控件的名称构建为字符串并将其作为键传递给控件集合。

标签: excel vba loops checkbox userform


【解决方案1】:

作为对我评论的后续回答,我认为您正在寻找以下内容:

    arow = lastAns - qRow
    Dim i As Long, ctl As Control
    For i = 1 To 4
        Set ctl = Me.Controls("CheckBox" & i)
        If i <= arow Then
            ctl.Visible = True
            ctl.Caption = Cells(qRow + i - 1, 5)
        Else
            ctl.Visible = False
        End If
    Next i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2021-10-07
    相关资源
    最近更新 更多