VBA UserForm具有相同值的多个组合框

时间:2017-11-03 09:43:32

标签: excel vba excel-vba combobox userform

我想在Excel用户窗体中制作3个不同的组合框。总共会有每种类型的x。

我想制作一个这样的代码:

With ComboboxAi for i = 1 to 5
    .AddItem "monday"
    .AddItem "tuesday"

With ComboboxBj for j = 1 to 6
    .AddItem "january"
    .AddItem "february"

我的组合框命名如下: ComboboxA1,..,ComboboxA5,ComboboxB1,..,ComboboxB6

有人可以帮我制作正确的代码吗?

1 个答案:

答案 0 :(得分:2)

这是语法:

    Dim i As Long

    For i = 1 To 5
        With Controls("ComboboxA" & i)
            .AddItem "Monday"
            .AddItem "Tuesday"
        End With
    Next i

    For i = 1 To 6
        With Controls("ComboboxB" & i)
            .AddItem "January"
            .AddItem "February"
        End With
    Next i

然而,以下可能是实现同样目标的更好方法:

    Dim ctrl As MSForms.Control

    For Each ctrl In Controls
        If TypeOf ctrl Is MSForms.ComboBox Then
            If ctrl.Name Like "ComboboxA*" Then ctrl.List = Array("Monday", "Tuesday")
            If ctrl.Name Like "ComboboxB*" Then ctrl.List = Array("January", "February")
        End If
    Next ctrl