【问题标题】:How to filter data in combo Box vba如何在组合框 vba 中过滤数据
【发布时间】:2022-01-06 13:58:11
【问题描述】:

我陷入了这个问题,我必须将数据过滤到组合框中。该列表应该只有唯一的记录。 这是将记录填充到组合框中的代码:

Private Sub UserForm_Activate()
Dim myrng As Range
Dim cl As Range
Dim sh As Worksheet
Set sh = Worksheets("Product_Master")

        Set myrng = sh.Range("C2:C100000")
        With Me.comBox_Purchase_Product
            .Clear
            For Each cl In myrng.Cells
                If cl.Value <> "" Then
                    .AddItem cl.Value
                End If
            Next cl
        End With
    End sub 

这是我得到的产品...现在我只想要唯一的记录并删除所有重复项。

提前致谢。

【问题讨论】:

标签: excel vba combobox duplicates unique


【解决方案1】:

首先将所有值添加到dictionary。添加时,使用myDictionary.Exists 测试唯一性。然后从字典中获取唯一列表以加载到组合框列表中。

Private Sub UserForm_Activate()
    Dim sh As Worksheet
    Set sh = Worksheets("Product_Master")
    
    Dim myrng As Range
    Set myrng = sh.Range("C2:C100000")
    
    Dim Dict As Object
    Set Dict = CreateObject("Scripting.Dictionary")
    
    Dim cl As Range
    For Each cl In myrng.Cells
        If cl.Value <> "" And Not Dict.exists(cl.Value) Then
            Dict.Add cl.Value, 0
        End If
    Next cl

    Me.comBox_Purchase_Product.List = Dict.Keys
End Sub

我建议将事件从 UserForm_Activate 更改为 UserForm_Initialize,因为这样可以避免重复运行脚本太多次,但它在两个事件中都可以工作。

【讨论】:

  • 那行得通。谢谢你:)
猜你喜欢
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2020-09-17
  • 2023-02-16
  • 2015-07-26
  • 2012-10-09
相关资源
最近更新 更多