在VBA Excel中以编程方式将OptionButtons添加到Userform

Anu*_*nup 4 excel vba label excel-vba

我对VBA编程很新.我的场景是我将获得一个字符串值列表我需要使用小窗口上的单选按钮向用户显示这些值,以便每当用户通过单击单选按钮选择任何值时,我应该能够获得该值在VBA代码中.我在互联网上搜索用户表单中的添加选项按钮我得到了一些使用GUI方法创建选项按钮的解决方案.但我需要通过程序完成它.我在stackoverflow中找到了一个有用的线程(如何使用VBA在表单上动态添加一个单选按钮)我使用了这个,但我仍然无法在用户表单上获得任何标签或按钮,将显示一个普通的用户表单.所以任何人都请提供相关信息.

代码是:

Sub Button1_Click()
    lResult As Variant    ' this is a array which contains string vaues to be dispayed as radio button.

    ' Some operatin is done here to get the list of values in lResult

    Dim rad As Variant
    Set rad = UserForm1.Controls.Add("Forms.OptionButton.1", "radioFoo", True)
    rad.Caption = "bar"
    rad.Left = 10
    rad.Width = 10
    rad.Top = 10
End Sub
Run Code Online (Sandbox Code Playgroud)

UserForm1是我在VBA菜单栏中使用"插入"选项创建的用户窗体.我试图在userform上添加一个按钮.我没有在userform上使用initialize函数.excel工作表上有按钮Button1我点击该按钮调用此功能.

谢谢

Rip*_*ter 6

如果您有一个名为UserForm1包含名为的按钮的表单CommandButton1

用户窗体



您可以为UserForm设置Initialize方法,以编程方式创建一组单选按钮

Private Sub UserForm_Initialize()
    Dim OptionList(1 To 3) As String
    Dim btn As CommandButton
    Set btn = UserForm1.CommandButton1
    Dim opt As Control
    Dim s As Variant
    Dim i As Integer

    OptionList(1) = "Option 1"
    OptionList(2) = "Option 2"
    OptionList(3) = "Option 3"

    For Each s In OptionList
        Set opt = UserForm1.Controls.Add("Forms.OptionButton.1", "radioBtn" & i, True)
        opt.Caption = s
        opt.Top = opt.Height * i
        opt.GroupName = "Options"

        UserForm1.Width = opt.Width
        UserForm1.Height = opt.Height * (i + 2)

        i = i + 1
    Next

    btn.Caption = "Submit"
    btn.Top = UserForm1.Height - btn.Height + (0.5 * opt.Height)
    btn.Left = (UserForm1.Width * 0.5) - (btn.Width * 0.5)

    UserForm1.Height = UserForm1.Height + btn.Height + (0.5 * opt.Height)
End Sub

Private Sub CommandButton1_Click()
    Dim i As Integer

    For i = 0 To UserForm1.Controls.Count - 1
        If UserForm1.Controls(i) Then
            SelectedOption = UserForm1.Controls(i).Caption
        End If
    Next

    UserForm1.Hide
End Sub
Run Code Online (Sandbox Code Playgroud)



如果您想从工作表中提取列表,则可以更改

Dim OptionList(1 To 3) As String

OptionList(1) = "Option 1"
OptionList(2) = "Option 2"
OptionList(3) = "Option 3"
Run Code Online (Sandbox Code Playgroud)

从这样的范围拉出来

Dim OptionList() as Variant
OptionList = Range("A1:A3")
Run Code Online (Sandbox Code Playgroud)


在存储在模块中的"button_onclick()"过程中添加以下代码:

'This is set by the code in UserForm1
Public SelectedOption As String

Sub Button1_OnClick()
    UserForm1.Show
    MsgBox SelectedOption
End Sub
Run Code Online (Sandbox Code Playgroud)



哪个得到了这个结果:

在此输入图像描述

当您单击"提交"时,将弹出一个消息框,显示您选择了哪个选项

在此输入图像描述