【问题标题】:How can we create multiple dependent drop down list in Excel using VBA我们如何使用 VBA 在 Excel 中创建多个依赖下拉列表
【发布时间】:2015-07-24 10:09:45
【问题描述】:

我需要两个相关的下拉列表。在 VBA 中,我尝试为单个列表创建下拉列表,但我无法使其依赖。下拉列表就像

第一个下拉列表的内容

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/

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

或者是否有任何方法可以使用公式直接创建相关下拉列表,并消除两列中的空白单元格。

提前致谢

【问题讨论】:

标签: vba excel excel-2007


【解决方案1】:

您必须将这些值的关系存储在某处。然后当一个被选中时填充另一个。这是一个将值存储在 A 列和 B 列中的示例。

A   B
--- ----
dd1 ddd1
dd1 ddd2
dd1 ddd3
dd2 ddd4
dd2 ddd6

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2013-10-19
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2019-10-20
    相关资源
    最近更新 更多