我一直在互联网上寻找答案,但大多数人都说使用数据验证,这并没有真正解决我的问题。我要做的是,假设我有ListBox1,它有3个值(红色,蓝色,绿色),还有另一个列表框(ListBox2),我希望根据答案显示工作表中的列表值第一个ListBox。例如:我从listbox1中选择红色,然后我想在listbox2中列出“red”(apple,coke,fire)列表中的选项。 我非常感谢你的一些帮助。感谢
答案 0 :(得分: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
答案 1 :(得分: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
这是两个列表框属性的样子:
如果您想下载这个优雅的模板click here.