Self VBA application (13) - two ComboBox

Now we have two columns of data shown in FIG
Here Insert Picture Description
needed to make the effect of the following form
Here Insert Picture Description

  • First, let's draw a diagram similar to the two composite housing
    Here Insert Picture Description
  • Type the following code in the event UserForm_Initialize
Private Sub UserForm_Initialize()
    Dim i As Long, j As Long
    Dim col As New Collection
    Dim rng As Range
    Dim arr()
    On Error Resume Next
    i = Sheet5.Cells(Rows.Count, 1).End(xlUp).Row
    For Each rng In Sheet5.Range("a2:a" & i)
        col.Add rng, CStr(rng)
    Next
    '集合添加元素,可以达到去重效果
    ReDim arr(1 To col.Count)
    For i = 1 To col.Count
        arr(i) = col(i)
    Next
    ComboBox1.List = arr
    ComboBox1.ListIndex = 0
    Set col = Nothing
    Set rng = Nothing
End Sub
  • Finally, type the code in the event ComboBox1_Change
Private Sub ComboBox1_Change()
    Dim str As String
    Dim rng As Range
    ComboBox2.Clear
    With Sheet5.Columns(1)
        Set rng = .Find(What:=ComboBox1.Text)
        If Not rng Is Nothing Then
            str = rng.Address
            Do
                ComboBox2.AddItem rng.Offset(, 1)
                Set rng = .FindNext(rng)
            Loop While Not rng Is Nothing And _
            rng.Address <> str
        End If
    End With
    ComboBox2.ListIndex = 0
    Set rng = Nothing
End Sub

Such a combination of two interlocking frame is complete it!

Published 24 original articles · won praise 9 · views 1044

Guess you like

Origin blog.csdn.net/qq_24818403/article/details/103939315