Excel用户窗体:组合框用于填充文本或列表框

时间:2019-10-11 09:22:44

标签: excel vba combobox

Excel VBA:我正在使用组合框,我需要在文本框或列表框中填充信息。组合框从E列获取值(E包含重复的日期)。因此,组合框必须包含唯一值。然后在列表框中,我想要相应行中的信息。 例如。如果在E列中,则10月1日至10日是10月5日至10日的两倍。因此,我希望组合框采用唯一的日期,即10月1日至10日。如果我选择10月7日,则在列表框中它应显示与10月7日日期相对应的两个条目的数据。而且,我需要的字段在G,J,K,L,M列中。 如果可以在用户表单中以不同的方式可视化它,请提出建议。

我正在研究以下代码。

'=========================================================================================

'For collecting unique value in userform combobox
Private Sub UserForm_Initialize()

    UserForm2.ComboBox1.Clear

Dim v, e
With Sheets("Atorvastatin").Range("E2:E1000")
    v = .Value
End With

With CreateObject("scripting.dictionary")
    .comparemode = 1
    For Each e In v
        If Not .exists(e) Then .Add e, Nothing
    Next
    If .Count Then Me.ComboBox1.List = Application.Transpose(.keys)
End With

    Set xRg = Sheets("Atorvastatin").Range("E2:Q1000")

End Sub

'--------------------------------------------------------------------------------------------

Private Sub ComboBox1_Change()

    Dim var1 As Long
    Me.TextBox1 = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, xRg, 3, False)

End Sub

1 个答案:

答案 0 :(得分:0)

要填充ListBox1,您可以使用以下代码:

Private Sub ComboBox1_Change()

    Dim f As Range
    Dim firstAddress As String

    Set f = xRg.Find(what:=Me.ComboBox1.Value, LookIn:=xlValues, lookat:=xlWhole) ' always specify at least 'LookIn' and 'LookAt' parameters, or they will be set as per last 'Find()' usage (even from Excel UI!)
    If Not f Is Nothing Then ' if a match found
        With Me.ListBox1 
            '.Clear ' uncomment to have ListBox1 filled with elements corresponding with current ComboBox1 selected element only
            firstAddress = f.Address ' store first matched cell address
            Do
                .AddItem f.Offset(, 2).Value ' add currently matched cell2 columns to the right value 
                Set f = xRg.FindNext(f) ' search for next occurrence
            Loop While f.Address <> firstAddress ' exit do when hitting first found cell again
        End With
    End If

End Sub

这样,只需将xRG设置为E列即可

Private Sub UserForm_Initialize()

    Me.ComboBox1.Clear

    Dim v, e
    With Sheets("Atorvastatin") 
        With .Range("E2", .Cells(.Rows.Count, "E").End(xlUp))
            Set xRg = .Cells ' set xRG to column E range only
            v = .Value
        End With
    End With

    With CreateObject("scripting.dictionary")
        .comparemode = 1
        For Each e In v
            If Not .exists(e) Then .Add e, Nothing
        Next
        If .Count Then Me.ComboBox1.List = Application.Transpose(.keys)
    End With


End Sub