2010-01-12 54 views
1

我想动态地添加一个窗体上的单选按钮,使用VBA。我怎样才能动态地添加一个单选按钮在窗体上使用VBA

我试着写这个代码,但它与“类型不匹配”

Dim optionBtn As OptionButton 
Set optionBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "name", True) 

optionBtn.Left = 10 
optionBtn.Top = 10 
optionBtn.Width = 30 
optionBtn.Group = "q1" 

我也试着这样做崩溃:

Dim optionBtn As Control 
Set optionBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "name", True) 

optionBtn.Left = 10 
optionBtn.Top = 10 
optionBtn.Width = 30 
optionBtn.Group = "q1" 

,但我得到了控制,而不是一个选项按钮 - 怎么能我把它投给了一个OptionButton? (对不起,我是新来的VB)

回答

2

我能得到它与该作品(Excel 2003中):

Dim lbl As Variant 

Set lbl = UserForm1.Controls.Add("Forms.Label.1", "lblFoo", True) 
lbl.Caption = "bar" 

更新,以反映从标签到一个选项按钮的变化

再次,关键是使用的变量,你是指派返回控制给Variant类型:

Dim opt As Variant 

Set opt = UserForm1.Controls.Add("Forms.OptionButton.1", "radioFoo", True) 
opt.Caption = "Bar" 

请记住,自动完成功能不适用于定义为变体的变量。但是,您仍然可以通过手动输入变量来引用这些变量的属性和方法。

0

mark的代码应该可以工作,但我通常更喜欢手动创建该项目,然后根据需要显示/隐藏它。

+1

这一切都取决于你想要做什么。我曾经遇到过显示表单的情况,这取决于电子表格中的信息。在这种情况下,创建动态控件几乎是处理它的唯一方法。 – 2010-01-12 19:45:28

+0

我同意。如果我只需要取消隐藏,我就不得不始终创建它们......很难从问题中看出OP是从哪里来的。 只要我们抛出选项......我还将使用多页工具并隐藏选项卡来控制表单流。 – guitarthrower 2010-01-12 23:07:07

0

您需要将对象定义为msforms库中的optionbutton。

Dim optionBtn As MSForms.OptionButton 
Set optionBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "name", True) 
1

其实,我相信你的问题在于你将optionBtn命名为对象按钮。它需要被命名为MSForms选项按钮。由于Variant可以是一个对象,因此它在使用变体时会起作用。

我用下面的,它工作正常。

Dim TempForm As Object 
Dim newOptionButton as MSForms.OptionButton 
Dim sUserformName as string 
Dim i as integer 
Dim x as integer 
Dim y as integer 
' other junk removed for example sake... 


sUserformName = sheet1.cells(1,1) 

' create form 
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3) 
With TempForm 
    .Properties("Caption") = sUserformName 
    .Properties("Width") = 450 
    .Properties("Height") = 300 
End With 

for i = 3 to sheet1.range("A65536").End(XlUp).Row 
sDefault = sheet1.cells(i,5) 
iGN = sheet1.cells(i,6) 


' additional code removed... for sake of example... the code would add labels, text boxes, etc... 

    Set newOptionButton = TempForm.designer.Controls.Add("Forms.optionbutton.1") 
    With newOptionButton 
     .Caption = sDefault 
     .GroupName = "Group" & iGN 
     .Top = 20 + (20 * x) 
     .Left = y 
     .Height = 16 
     .Font.Size = 8 
     .Font.Name = "Ariel" 
    End With 

“这里的代码的变化x和y依赖于在用户(Excel模板)指示的下一个控制。

下一个我

好运....