使用高级过滤器在用户窗体中填充列表框

时间:2018-09-21 07:38:32

标签: excel vba excel-vba

我有一个主表,其中A列包含“客户名称”,B列包含“频率”,必须将报告发送给这些客户。重复如下所示的客户端名称 enter image description here

我的用户表单有一个组合框,它将从B列获取频率详细信息,还有一个列表框,将从B列填充数据,即唯一的客户端名称。 Form screenshot

经过研究,我可以使用“高级”过滤器选项使用以下代码填充客户列表框数据。

Dim arrUnqItems As Variant

        With Sheets("Data")

            .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).AdvancedFilter xlFilterCopy, , .Cells(1, .Columns.Count), True
            arrUnqItems = Application.Transpose(.Range(.Cells(2, .Columns.Count), .Cells(.Rows.Count, .Columns.Count).End(xlUp)).Value)
            .Columns(.Columns.Count).Clear

        End With

        Me.custList.Clear
        Me.custList.List = arrUnqItems

        Erase arrUnqItems

但是此列表框代码不是根据组合框选择来过滤值,而是仅显示唯一的客户名称。有人可以帮忙吗?然后,基于对组合框和列表框的选择,我将搜索数据库以获取客户的其他详细信息,并将其填充到表单的其他部分。

1 个答案:

答案 0 :(得分:0)

您必须写下CriteriaRange字段的范围:

    Dim freq As String
    freq = Combobox1.Value ' get the currently selected frequency (change "Combobox1" to your actual frequency combobox name)
    With Sheets("Data")
        .Cells(1, .Columns.Count - 2).Resize(2) = Application.Transpose(Array("Frequency", freq )) 'write the "CriteriaRange" in the third last column
        .Range("B1", .Cells(.Rows.Count, "A").End(xlUp)).AdvancedFilter xlFilterCopy, .Cells(1, .Columns.Count - 2).Resize(2), .Cells(1, .Columns.Count - 1), True ' filter adopting the written "CriteriaRange" and paste filtered values from the second last column (two columns will be pasted: "Customer Name" and "Frequency")
        arrUnqItems = Application.Transpose(.Range(.Cells(2, .Columns.Count - 1), .Cells(.Rows.Count, .Columns.Count - 1).End(xlUp)).Value) ' fill array of unique customer names from the second last column
        .Columns(.Columns.Count - 2).Resize(, 3).Clear
    End With