EXCEL VBA Combobox匹配

时间:2013-01-11 08:37:59

标签: excel vba combobox

说明: enter image description here 图片1

基于Image1,Level 1是Object,Level 2是对象的类型。

enter image description here
图像2

在图2中,您可以看到我分别为ComboBox1ComboBox2命名了Level 1Level 2

我想要实现的目标:

  1. 当用户选择ComboBox1时,它会显示一组Level 1项,如A2:XFD2中没有空单元格的图片所示。
  2. 然后,根据ComboBox1中的选择,ComboBox2将根据{{1}中的值列出图像1 中显示的Level 2 }。
  3. 提前致谢

1 个答案:

答案 0 :(得分:1)

将此添加到您的用户表单代码:

Private Sub UserForm_Initialize()

Dim rnLevel1 As Range, rnLevel2 As Range, rnTemp As Range

Set rnLevel1 = Sheet1.Cells(2, Sheet1.UsedRange.Columns.Count)

ComboBox2.Clear 'Clear all values first

For Each rnTemp In rnLevel1
    If rnTemp.Value <> "" And rnTemp.Value <> "Level 1" Then ' Add values NOT INCLUDING Level 1 to Combobox1
        ComboBox1.AddItem rnTemp.Value
    End If
Next


End Sub

Private Sub ComboBox1_Change()
Dim rnLevel1 As Range, rnLevel2 As Range, rnTemp As Range

Set rnLevel1 = Sheet1.Cells(2, Sheet1.UsedRange.Columns.Count).Find(ComboBox1.Value) 'Find the correct column
Set rnLevel2 = Sheet1.Range(rnLevel1.Offset(1, 0), Sheet1.Cells(Sheet1.Rows.Count, rnLevel1.Column).End(xlUp))

ComboBox2.Clear 'Clear all values first

For Each rnTemp In rnLevel2
    If rnTemp.Value <> "" Then  ' Add values to Combobox2
        ComboBox2.AddItem rnTemp.Value
    End If
Next

End Sub