VBA 组合框列表(按条件)

VBA ComboBox List by Criteria

我正在尝试使用用户窗体组合框创建列表。该列表将从电子表格中获取数据,这些数据可以更新并推回电子表格。但是,在按条件创建列表时,我迷路了。

我有范围 (A:A),其中有任务标题。在范围 (D:D) 中,我有任务的状态(进行中、待检查、已批准和已发布)。我要创建的列表是列出任务标题,其中 D=For Check.

能否请您指出正确的方向,以便能够在 VBA 中编写此内容?

例如,您可以将以下代码添加到用户表单

Option Explicit


Private Sub UserForm_Initialize()

    ' I assume the list is on the Activesheet
    ' and it has a header row
    Dim rg As Range
    Set rg = Range("A1").CurrentRegion
    Set rg = rg.Offset(1).Resize(rg.Rows.Count - 1)

    Dim vDat As Variant

    ' Goto Tools/References and check Microsoft Scripting Runtime
    Dim rDict As Scripting.Dictionary
    Set rDict = New Scripting.Dictionary

    vDat = rg.Value2

    Dim i As Long
    For i = LBound(vDat) To UBound(vDat)
        ' If column D contains "For Check"
        ' add the task from column A to the dictionary
        If vDat(i, 4) = "For Check" Then
            rDict(vDat(i, 1)) = vDat(i, 1)
        End If
    Next i

    ' I assume the name of the combobox is combobox1
    ComboBox1.List = rDict.Keys
End Sub