简体   繁体   English

使用UserForm控件名称的For Next Loop值构建字符串

[英]Building a string with For Next Loop value for a UserForm control name

I'm trying to build the value 我正在努力建立价值

If UserForm1.p1OptionButton.Value = True

Where the 1 in p1OptionButton is the value of a For Next loop counter but I'm getting errors however I try and construct it. p1OptionButton中的1是For Next循环计数器的值,但我收到错误但是我尝试构造它。 If I use 如果我使用

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

I get this error: 我收到此错误:

Runtime error 13 type mismatch. 运行时错误13类型不匹配。

If I leave the " out from around the other parts of the string it doesn't work either. 如果我离开“从字符串的其他部分周围出来它也不起作用。

Thanks for your help. 谢谢你的帮助。

Say for example you have 6 OptionButton s and a CommandButton on your form then you can iterating the options per the code sample below. 比如说你的表单上有6个OptionButton和一个CommandButton ,那么你可以根据下面的代码示例迭代选项。 If you set a variable to be an OptionButton and then assign one of the forms Controls to that variable you can access its properties eg Name and Value etc very easily. 如果将变量设置为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

Been a long time since I have done any VBA so may be a bit rusty :) 很长一段时间以来我做过任何VBA所以可能有点生锈:)

The error you are getting is because you are comparing a String with a Boolean, hence the Type Mismatch 您得到的错误是因为您正在将String与布尔值进行比较,因此类型不匹配

You could try using the following code to access a control dynamically: 您可以尝试使用以下代码动态访问控件:

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

I believe you're trying to compare a string to a boolean value, so it's not going to work in the way you want it to. 我相信你正在尝试将字符串与布尔值进行比较,因此它不会按照你想要的方式工作。 If you want it to work better, you could do something similar to simply just going through each of the possible values (IE UserForm1.p1OptionButton.Value, UserForm1.p2OptionButton.Value, etc) 如果你想让它更好地工作,你可以做类似的事情只是简单地浏览每个可能的值(IE UserForm1.p1OptionButton.Value,UserForm1.p2OptionButton.Value等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM