ListFillRange的ActiveX ComboBox动态范围

时间:2019-04-17 14:51:22

标签: excel vba

我上面有ThisWorkbook.Sheets("MAIN")和ActiveX ComboBox11。我也有桌子:

         A                    B 
1      John 1               10000
2      John 2               20000
3      John 3               20000
4      John 4               10000
5      John 5               50000
6      John 6               50000
7      John 7               50000
8      John 8               10000
9      John 9               20000
10     John 10              50000

然后在单元格Q10中我有值,例如32000

我想在ActiveX ComboBox11中动态显示列A范围,条件是:

=IF(B1<Q10;"not in list";A1))

,这样我在ActiveX ComboBox11下拉菜单中的值就不会小于32000。

在这种情况下,ActiveX ComboBox11看起来像:

John 5
John 6
John 7
John 10

在ListFillRange中命名范围很容易。但是我想有一个动态范围。有什么想法要实现吗?

我需要以某种方式使用过滤器吗?

Private Sub Worksheet_Change(ByVal Target As Range)

   'If Target.Address = Range("Q10").Address Then
       'Range("A1:B10").CurrentRegion.AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=Range("B1:B10")
   'End If

End Sub

然后在ActiveX ComboBox11 ListFillRange中使用过滤范围吗?

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。您可以循环所有行,找到大于3200的值,将其复制到“隐藏”工作表中,完成循环后,从该“隐藏”工作表中获取“范围”并将其分配给ListFillRange。示例:

Function updateCombo1()
    Dim lastRow As Long, i As Long, x As Long, wk As Workbook
    Set wk = ThisWorkbook
    With wk.Sheets("Sheet1")
        lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        wk.Sheets("HiddenSheet").Cells.ClearContents
        For i = 1 To lastRow
            If .Cells(i, 3).Value >= .Range("G10").Value Then
                x = x + 1
                wk.Sheets("HiddenSheet").Cells(x, 1).Value = .Cells(i, 2).Value
            End If
        Next i
        lastRow = wk.Sheets("HiddenSheet").Cells(Rows.Count, 1).End(xlUp).Row
        'If Form DropDown, Set Range
        .DropDowns("Drop Down 2").ListFillRange = "HiddenSheet!A1:A" & lastRow
        'If ActiveX DropDown, Set Range
        .ComboBox11.ListFillRange = "HiddenSheet!A1:A" & lastRow
    End With
End Function

您还可以循环所有行,并在下拉列表中一一添加。示例:

Function updateCombo2()
    Dim lastRow As Long, i As Long, wk As Workbook
    Set wk = ThisWorkbook
    With wk.Sheets("Sheet1")
        lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        'If Form Drop Down, Clear All Items
        .DropDowns("Drop Down 2").RemoveAllItems
        'If ActiveX Drop Down, Clear All Items
        .ComboBox11.Clear
        For i = 1 To lastRow
            If .Cells(i, 3).Value >= .Range("Q10").Value Then
                'If Form DropDown, Add Item
                .DropDowns("Drop Down 2").AddItem .Cells(i, 2).Value
                'If ActiveX DropDown, Add Item
                .ComboBox11.AddItem .Cells(i, 2).Value
            End If
        Next i
    End With
End Function

只需在Worksheet_Change上调用函数

编辑:使用ActiveX下拉菜单要简单得多,但是出于兼容性考虑,我会尝试使用Form Drop Down。