我需要VBA代码,它将从列'A'中查找值,并在userform combox1中将相邻的水平非空白单元格列在右侧。
示例数据:
+-----+----+----+----+---+
| A | B | C | D | E |
+-----+----+----+----+---+
| A1 | 63 | | 55 | 5 |
+-----+----+----+----+---+
Sudo Code:
Sub test()
myVal = “A1”
Findme = myVal
Set match = Sheets(“Sheets1”).Range(A:A).Find(Findme)
myRange = foundRange
Userform1.Combobox.value = myRange
Exit Sub
在上面的示例代码中,foundRange将是找到值的行,加上列'B'到'E',减去任何空格。
Combobox值:
63 55 56
谢谢!
答案 0 :(得分:1)
创建名为 Userform1 的Userform,名为 ComboBox 的ComboBox和名为 CommandButton1 的按钮。如下图所示:
然后在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
此代码使用您要用于在ComboBox .Find
上添加项目的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
设置为您正在使用的范围。例如:您的整个工作表