【问题标题】:Building a string with For Next Loop value for a UserForm control name为用户窗体控件名称构建具有 For Next Loop 值的字符串
【发布时间】:2017-08-02 02:20:17
【问题描述】:

我正在努力建立价值

If UserForm1.p1OptionButton.Value = True

p1OptionButton 中的 1 是 For Next 循环计数器的值,但我遇到了错误,但我尝试构建它。如果我使用

Dim iPart As Integer
For iPart = 1 to 6
If "UserForm1.p" & iPart & "OptionButton.Value" = True
.... blah blah blah rest of the code
Next iPart

我收到此错误:

运行时错误 13 类型不匹配。

如果我将 " 从字符串的其他部分排除在外,它也不起作用。

感谢您的帮助。

【问题讨论】:

    标签: vba excel for-loop userform


    【解决方案1】:

    假设您的表单上有 6 个OptionButtons 和一个CommandButton,那么您可以按照下面的代码示例迭代选项。如果您将变量设置为OptionButton,然后将Controls 的一种形式分配给该变量,您可以访问其属性,例如NameValue 等非常容易。

    Option Explicit
    
    Private Sub CommandButton1_Click()
    
        Dim opt As MSForms.OptionButton
        Dim i As Long
    
        For i = 1 To 6
            Set opt = UserForm1.Controls("p" & i & "OptionButton")
            If opt.Value = True Then
                MsgBox opt.Name & ":" & opt.Value
            End If
        Next i
    End Sub
    

    【讨论】:

    • 这是正确的方法,我相应地对其进行了投票,但值得注意的是,尽管控件集合是基于 0 的,但您实际上是按其名称而不是其序数来选择 opt。在您的示例中,当 i = 0 时 'UserForm1.Controls("p" & i + 1 & "OptionButton")' 评估为 'UserForm1.Controls("p1OptionButton")' 所以您不妨使用让您的生活更轻松'对于 i = 1 到 6' 和 'UserForm1.Controls("p" & i & "OptionButton")'。
    • @Winterknell - 是的,当然,你是对的。我将更新示例。
    【解决方案2】:

    很久没做VBA了,可能有点生疏了:)

    您得到的错误是因为您将字符串与布尔值进行比较,因此类型不匹配

    您可以尝试使用以下代码动态访问控件:

    Forms("UserForm1").Controls("p" & iPart & "OptionButton").Value = True
    

    【讨论】:

      【解决方案3】:

      我相信您正在尝试将字符串与布尔值进行比较,因此它不会按照您想要的方式工作。如果你想让它工作得更好,你可以做一些类似于简单地检查每个可能的值(IE UserForm1.p1OptionButton.Value、UserForm1.p2OptionButton.Value 等)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 2016-04-10
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多