【问题标题】:Populating combobox with dynamic horizontal range使用动态水平范围填充组合框
【发布时间】:2018-02-20 05:19:09
【问题描述】:

我需要 VBA 代码,该代码将从“A”列中查找一个值,并在用户表单组合框 1 中列出右侧相邻的水平非空白单元格。

样本数据:

+-----+----+----+----+---+
|  A  | B  | C  | D  | E |
+-----+----+----+----+---+
|  A1 | 63 |    | 55 | 5 |
+-----+----+----+----+---+

须藤代码:

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”,减去任何空白。

组合框值:

63 55 56

谢谢!

【问题讨论】:

    标签: excel combobox range userform vba


    【解决方案1】:

    创建一个名为 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 可以设置为您正在使用的范围。例如:您的整个工作表

    【讨论】:

    • 效果很好。谢谢,谢谢,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2018-08-03
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多