【发布时间】:2015-12-05 06:01:31
【问题描述】:
我试图让我的 combobox2 显示基于我在我的 combobox1 中所做的选择的值,这样只有与 combobox1 相关的数据才会显示在 combobox2 中。例如,如果用户在组合框 1 中选择“水果”,则组合框 2 中只会显示“苹果、橙子...”(即使我的数据范围有水果、蔬菜、面包等)。我已经修改了一些我发现的代码该组合框1 根据我的数据范围显示值。任何人都可以协助进一步修改代码,以便 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
谢谢!
【问题讨论】:
-
您可以在 vba 之外执行此操作,请参阅 here
-
我的偏好是使用 VBA 来执行此操作,因为我的数据集将不断更新和更改。