创建一个名为 Userform1 的用户窗体、名为 ComboBox 的 ComboBox 和名为 CommandButton1 的 Button。如下图所示:
然后在 commandButton 上使用此代码来填充 ComboBox:
Private Sub CommandButton1_Click()
Dim ws1 As Worksheet
Dim i As Long, c As Long
Dim rng As Range, rng2 As Range
Dim cellFound As Range
Dim lastrow As Long, lastcolumn As Long
Set ws1 = ThisWorkbook.Sheets(1)
Findme = "A1"
lastrow = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
Set rng = ws1.Range("A:A") 'range to search
Set rng2 = rng(lastrow, 1)
With rng
Set cellFound = .Find(what:=Findme, After:=rng2, LookIn:=xlValues)
If Not cellFound Is Nothing Then
FirstAddress = cellFound.Address
Do
lastcolumn = ws1.Cells(ws1.Range(cellFound.Address).Row, ws1.Columns.Count).End(xlToLeft).Column
For i = Range(cellFound.Address).Column + 1 To lastcolumn
If ws1.Cells(Range(cellFound.Address).Row, i) <> "" Then ComboBox.AddItem ws1.Cells(Range(cellFound.Address).Row, i).Value
Next i
Set cellFound = .FindNext(cellFound)
Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
End If
End With
End Sub
此代码使用您想使用的 .Find 函数在 ComboBox ComboBox.AddItem 上添加项目。请注意,代码在 Userform 内部,否则需要进行一些更改才能使其全局化。
找到 A1 后,您使用它的地址行来获取最后一列。并通过 CellFound + 1Column (样本上的 2)循环到最后一列,比较值是否与空白不同。如果不同,则添加到 ComboBox。
lastcolumn = ws1.Cells(ws1.Range(cellFound.Address).Row, ws1.Columns.Count).End(xlToLeft).Column
For i = Range(cellFound.Address).Column + 1 To lastcolumn
If ws1.Cells(Range(cellFound.Address).Row, i) <> "" Then ComboBox.AddItem ws1.Cells(Range(cellFound.Address).Row, i).Value
Next i
然后找到下一个值并做同样的事情,所以 A 列可以有多个匹配项。
Set cellFound = .FindNext(cellFound)
FindMe 值可以替换为任何值,例如 TextBoxes 或 Cell.Values。
搜索范围rng 可以设置为您正在使用的范围。例如:您的整个工作表