现在我们有两列数据如图所示
需要通过窗体做成如下效果
- 首先呢,我们画一个类似图中的两个复合框
- 在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
- 最后再在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
这样两个联动的组合框就完成啦!