【问题标题】:Combobox selection based on prior selection基于先前选择的组合框选择
【发布时间】: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 来执行此操作,因为我的数据集将不断更新和更改。

标签: excel vba


【解决方案1】:

试试这个,您不必使用高级过滤器来获取组合框1 的唯一项目。 一旦您从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

【讨论】:

  • 谢谢。我会测试一下。
  • 我测试过,但组合框没有返回任何值。只是空白。有任何想法吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多