我试图根据我在combobox1中做出的选择来显示我的combobox2显示值,以便只有与combobox1相关的数据才会显示在combobox2中。例如,如果用户在combobox1中选择“Fruit”,那么只有“苹果,橘子......”会显示在combobox2中(即使我的数据范围包含水果,蔬菜,面包等),我修改了一些我发现的代码。 combobox1根据我的数据范围显示值。任何人都可以帮助进一步修改代码,以便combobox2显示仅与combobox1选择相关的值。这是我的代码:
Private Sub ComboBox1_GotFocus()
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnData As Range
'Variant to conatin the data to be placed in the combo box
Dim vaData As Variant
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Analysis")
'Set the range equal to the data, and then (temporarily) copy the unique values of that data to the L column
With wsSheet
Set rnData = Range(.Range("B23"), .Range("B100000").End(xlUp))
rnData.AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=.Range("P23"), _
unique:=True
'Store the unique values in vaData
vaData = .Range(.Range("P24"), .Range("P100000").End(xlUp)).Value
'clean up the contents of the temporary data storage
.Range(.Range("P23"), .Range("P100000").End(xlUp)).ClearContents
End With
'display the unique values in vaData in the combobox already in existence on the worksheet
With wsSheet.OLEObjects("Combobox1").Object
.Clear
.List = vaData
.ListIndex = -1
End With
End Sub
谢谢!
答案 0 :(得分:0)
试试这个,您不必使用高级过滤器来获取combobox1的唯一项目。 从combobox1中选择后,将填充combobox2。我假设combobox2的值将在C列中,如果不是这样,则更改偏移量。
Private Sub ComboBox1_GotFocus()
Dim cUnique As Collection
Dim rng As Range
Dim Cell As Range
Dim sh As Worksheet
Dim vNum As Variant
Set sh = ThisWorkbook.Sheets("Analysis")
Set rng = sh.Range("B23", sh.Range("B23").End(xlDown))
Set cUnique = New Collection
On Error Resume Next
For Each Cell In rng.Cells
cUnique.Add Cell.Value, CStr(Cell.Value)
Next Cell
On Error GoTo 0
Me.ComboBox1.Clear
For Each vNum In cUnique
Me.ComboBox1.AddItem vNum
Next vNum
End Sub
Private Sub ComboBox1_Change()
Dim rws As Long, rng As Range, sh As Worksheet, c As Range
Set sh = ThisWorkbook.Sheets("Analysis")
With sh
rws = .Cells(.Rows.Count, "B").End(xlUp).Row
Set rng = .Range("B23:B" & rws)
End With
Me.ComboBox2.Clear
For Each c In rng.Cells
If c = Me.ComboBox1 Then
Me.ComboBox2.AddItem c.Offset(, 1)
End If
Next c
End Sub
另请查看此处的类似示例。
http://www.xlorate.com/excel-questions.html#Dependent%20ComboBox