我们如何使用VBA在Excel中创build多个从属下拉列表

我需要两个下拉列表,这是依赖的。 在VBA中,我尝试了单列表下拉列表的创build,但是我无法使其依赖。 下拉列表就像

首先下拉列表的内容

dd1 dd2 dd4 dd5 dd6 

相应的list2是

为dd1

 ddd1 ddd2 ddd3 

为dd2

 ddd4 ddd6 

像智者一样。

我已经完成了代码

 With Range("D1").Validation .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:=TempList .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With End If 

列表中不能有空格/空格。

我也试过这个

https://siddharthrout.wordpress.com/2011/07/29/excel-data-validationcreate-dynamic-dependent-lists-vba/

但是上面的代码支持单个单元格下拉菜单。 我需要列中的整个单元格作为下拉列表。

或者是否有任何方法直接创build依赖下拉列表使用公式消除两列的空白单元格。

提前致谢

您将不得不在某处存储这些值的关系。 然后当一个被选中填充另一个。 这是一个例子,如果这些值存储在列A和B.

 AB --- ---- dd1 ddd1 dd1 ddd2 dd1 ddd3 dd2 ddd4 dd2 ddd6 

在第一个列表的更改事件上,根据第一个列表中select的内容查找要放入第二个列表的内容。

 Private Sub ComboBox1_Change() Dim lRow As Long 'Clear out the second list ComboBox2.Clear lRow = 1 Do While lRow <= ws.UsedRange.Rows.Count If ws.Range("A" & lRow).Value = ComboBox1.Text Then 'Column A matches what was selected in the first list so add the value in columnB to the second list. ComboBox2.AddItem ws.Range("B" & lRow).Value End If lRow = lRow + 1 Loop End Sub 

如果你的数据存储在其他地方像数据库,

 Private Sub ComboBox1_Change() Dim strSQL as string 'Clear out the second list ComboBox2.Clear strSQL = "Select fieldname2 from tablename where fieldname1 = '" & ComboBox1.Text & "'" 'Put the results of the query into combobox2 End sub