如何控制另一个ComboBox?

时间:2011-12-18 01:07:06

标签: vba excel-2007

代码在UserForm中显示三个ComboBox。 Combobox2从工作表中选取四个值1,2,3,4(“数据”),从同一工作表中选择组合6个值(A,B,C,D,E,F)。  如果我想在Combobox2中选择值后控制Combobox3,我该怎么办,例如如果我选择1我只想A,B,C应该在Combobox3中,或者如果我选择2那么只有D,E找到Combobox3等?

提前感谢任何建议!

    Private Sub RapportFix_Initialize()
Dim ComboItems As Variant, i As Integer
Dim val As String

    With RapportFix.ComboBox2 'Provtyp
    .Clear ' remove existing entries from the listbox
    ComboItems = Worksheets("Indata").Range("C5:C8").Value
    ComboItems = Application.WorksheetFunction.Transpose(ComboItems)
    ' convert values to a vertical array
    For i = 1 To UBound(ComboItems)
        .AddItem ComboItems(i) ' populate the combobox
    Next i
   .ListIndex = -1 ' no items selected, set to 0 to select the first item
End With
With RapportFix.ComboBox3 'Kursplan
    .Clear ' remove existing entries from the listbox
    'Set sKursplanemoment = ComboBox3.Value
    ComboItems = Worksheets("Indata").Range("M5:M10").Value
    ComboItems = Application.WorksheetFunction.Transpose(ComboItems)
    ' convert values to a vertical array
    For i = 1 To UBound(ComboItems)
        .AddItem ComboItems(i) ' populate the combobox
    Next i
    .ListIndex = -1 ' no items selected, set to 0 to select the first item
 End With

 With RapportFix.ComboBox4 'Annat arbete
    .Clear ' remove existing entries from the listbox
    ComboItems = Worksheets("Indata").Range("E5:E8").Value
    ComboItems = Application.WorksheetFunction.Transpose(ComboItems)
    ' convert values to a vertical array
    For i = 1 To UBound(ComboItems)
        .AddItem ComboItems(i) ' populate the combobox
    Next i
    .ListIndex = -1 ' no items selected, set to 0 to select the first item
End With
RapportFix.Show
End Sub

1 个答案:

答案 0 :(得分:1)

每个用户表单控件都有许多与之关联的事件。 Cody建议的更改事件特别容易找到,因为您只需在设计视图中右键单击控件并选择“查看代码”,然后将填写子轮廓。

enter image description here

如上所示,代码页上方有两个下拉列表,一个列出可用的控件和对象,另一个列出事件。选择一个控件和一个事件来获取该事件的大纲子。

在这种特殊情况下,您需要使用控制组合的change事件首先清除然后重新填充依赖组合,就像您上面所做的那样。这些被称为级联组合。

Private Sub ComboBox2_Change()
    ''Populate combo 3
End Sub

唯一的区别是您需要检查列表是否仅包含应该为控制组合的每个值显示的项目。我倾向于使用我可以轻松控制的工作表上的列表来执行此操作:

Item2 Item3
1       a
1       b
2       d
2       c
3       a
3       e

但是,您似乎无法做到这一点,因此您可能希望使用Select Case

Private Sub ComboBox2_Change()
    Select Case ComboBox2
        Case "1", "2", "3"
            ''Add items x,y,z to combobox3
        Case "a", "b", "c"
            ''Add items m,n,o to combobox3
        Case Else
            ''Whatever
    End Select
End Sub