用UserForm控件名称构build用于下一​​个循环值的string

我正在努力build立价值

If UserForm1.p1OptionButton.Value = True 

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

 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 

我得到这个错误:

运行时错误13types不匹配。

如果我离开“从绳子的其他部分出来”,它也不起作用。

谢谢你的帮助。

举个例子,你在表单上有6个OptionButton和一个CommandButton ,然后你可以按照下面的代码示例迭代选项。 如果你设置一个variables为一个OptionButton ,然后指定一个窗体Controls到该variables,你可以很容易地访问它的属性,例如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 

过了很长时间,因为我做了任何VBA,所以可能有点生疏:)

你得到的错误是因为你比较一个string与布尔,因此types不匹配

您可以尝试使用以下代码来dynamic访问控件:

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

我相信你正试图比较一个string到一个布尔值,所以它不会以你想要的方式工作。 如果你想让它工作得更好,你可以做一些类似的事情,简单地通过每个可能的值(IE UserForm1.p1OptionButton.Value,UserForm1.p2OptionButton.Value等)