Userform列表框依赖于另一个列表框

问题描述 投票:0回答:2

我一直在网上寻找答案,但大多数人都说要使用数据验证,这并没有真正解决我的问题。我要做的是,假设我有ListBox1,它有3个值(红色,蓝色,绿色),还有另一个列表框(ListBox2),我希望根据答案显示工作表中的列表值第一个ListBox。例如:我从listbox1中选择红色,然后我想在listbox2中列出“red”(apple,coke,fire)列表中的选项。我非常感谢你的一些帮助。谢谢

excel vba excel-vba dependencies logic
2个回答
1
投票

你可以使用类似下面的东西(根据你的需要调整它):

Private Sub ListBox1_Click()
    With Me.ListBox2
        .Clear
        .List = Application.Transpose(GetColorItemsRange(Me.ListBox1.value)) 'fill referenced listbox with values from the range returned by GetColorItemsRange function
    End With
End Sub

Function GetColorItemsRange(colorValue As String) As Range
    With Worksheets("ColorItames") ' change "ColorItames" with actual name of your worksheet with items associated to colors
        With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft)).Find(what:=colorValue, LookIn:=xlValues, lookat:=xlWhole) 'find and reference the referenced sheet row 1 cell matching the passed value
            Set GetColorItemsRange = .Parent.Range(.Cells.Offset(1), .Cells.End(xlDown)) 'return the range ranging from referenced range down to last not empty cell before first empty cell
        End With
    End With
End Function

0
投票

数据验证是要走的路。您可能希望利用VBA的某些组合来调整listbox1更新后listbox2使用的范围。如果listbox1上只使用了1个选项,这相对容易。

希望您只有一个选择,因此您可以执行以下代码:

Private Sub ListBox1_Click()

If ListBox1.Selected(0) = True Then
    'Selection is apple. Adjust DynamicRange name for A1:A3
    ThisWorkbook.Names("DynamicRange").RefersTo = Range("A1:A3")

ElseIf ListBox1.Selected(1) = True Then
    ThisWorkbook.Names("DynamicRange").RefersTo = Range("B1:B3")

ElseIf ListBox1.Selected(2) = True Then
    ThisWorkbook.Names("DynamicRange").RefersTo = Range("C1:C3")

End If

End Sub

这是基于如下设置:enter image description here

这是两个列表框属性的样子:

enter image description here

如果你想下载这个优雅的模板,click here.

© www.soinside.com 2019 - 2024. All rights reserved.