在excel vba中创建用户定义的表单控件

时间:2018-06-14 09:30:06

标签: vba

我有一个excel用户表单,其中包含一个用于输入泵的组合框,组合框包含从1到30的下拉列表。如何根据用户选择创建新的表单控件?例如,如果用户选择5我想要创建5个名为pump1的标签,pump2到pump5都使用单选按钮进行产品选择。

1 个答案:

答案 0 :(得分:0)

您可以通过多种方式执行此操作,最简单的方法是,添加所有30个按钮并使用Private Sub ComboBox1_Change()子例程隐藏\取消隐藏它们。如果这不符合您的需求,那么您可能希望使用Microsoft Visual Basic for Applications Extensibility 5.3引用,在运行时添加按钮,然后在同一事件上修改它们。

示例用户窗体代码

''  Corresponding UserForm has *only* a combobox called `ComboBox1` located at left=6, top=6.

''  Form-level constants
Private Const maxNumBtns            As Integer = 12
Private Const defaultComBoxNum      As Integer = 5

''  Update buttons
Private Sub ComboBox1_Change()
    Dim comp            As Boolean
    ''  prevent flashing
    Let Application.ScreenUpdating = False
    For i = 1 To maxNumBtns
        With Me.Controls.Item(getBtnName(i))
            Let comp = i <= CInt(Me.ComboBox1.Value)
            ''  ensure hidden buttons are not pressed
            Let .Value = comp And .Value
            Let .Enabled = comp
            Let .Visible = comp
        End With
    Next
    Let Application.ScreenUpdating = True
End Sub

''  Set up UserForm
Private Sub UserForm_Initialize()
    Dim i               As Integer, _
        btn             As String
    For i = 1 To maxNumBtns
        ''  add line to combobox
        Call Me.ComboBox1.AddItem(i)
        Let btn = getBtnName(i)
        ''  add button
        Call Me.Controls.Add( _
            bstrProgID:="Forms.OptionButton.1", _
            Name:=btn, _
            Visible:=True)
        ''  Format the button
        With Me.Controls(btn)
            Let .Left = 12
            Let .Top = 30 + 17 * i
            Let .Width = 70
            Let .Height = 15
            Let .Caption = "Pump #" & i
        End With
    Next i
    'note: this calls combobox1_change
    Let Me.ComboBox1.Value = defaultComBoxNum
End Sub

''  helper function to ensure naming stays the same
Private Function getBtnName(ByVal index As Integer) As String
    Let getBtnName = " opBtn" & index
End Function

如果您希望使用带有复选框选项的组合框,则应使用listbox。 (您不需要此版本的可扩展性参考)

不幸的是,不可能隐藏列表框行,因此当更改组合框时,此选项需要删除列表框中的所有条目。

下面的方法对应一个useform,useform1,包含一个comboBox,pumpComboBox,一个listBox,pumpListBox和两个commandButtons,OkButton和{{1} }。

CancelButton