遍历工作表上的activeX ComboBox并将命名范围分配给listfill

时间:2019-04-10 22:53:49

标签: excel vba loops object combobox

我有A列和B列。B列中的每个单元格都包含一个activeX ComboBox。我想要的是根据A列中的输入(直接在组合框旁边),根据其他工作表中的命名范围填充B列中的ComboBox

为此,我需要使用嵌套的IF语句在工作表中的每个ComboBox上运行一个循环,但无法弄清楚如何在组合框对象中循环,然后为命名框分配命名范围(如果有)其他条件都成立。

为简单起见,单元格A1将位于ComboBox1旁边。单元格A2将位于ComboBox2等旁边。

基本示例:

myRange1 = ActiveWorkbook.Worksheets("Ranges").Range("NamedRange1")
myRange2 = ActiveWorkbook.Worksheets("Ranges").Range("NamedRange2")
i = 1

For Each ComboBox on ActiveWorksheet

If Cell("A" & i) 'condition1 here' Then
ComboBoxi.ListFillRange = myRange1
i = i+1
Elseif Cell("A" & i) 'condition2 here' Then
ComboBox'i'.ListFillRange = myRange2
i = i+1
Else 'do nothing

Next

1 个答案:

答案 0 :(得分:0)

我认为我找到了一种更清洁的方法。我没有意识到,即使这些范围位于单独的工作表中,您也不必为指定的范围指定工作表。在此示例中,"Range1""Range2"处于自己的工作表中。另外,它无需声明ComboBoxes为对象即可工作。 ComboBoxes保留为默认名称ComboBox1ComboBox2ComboBox3。 通过Populating combobox from named ranges

来到了这个解决方案

我敢肯定,有一种循环这种方法的好方法,而不是为if和关联的Range A1:A3中的每个唯一单元格做出唯一的ComboBox语句。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim result As String
Dim search1P As String
Dim search2P As String

search1P = "1P"
search2P = "2P"

If Not Intersect(Target, Range("A1:A3")) Is Nothing Then 'if target is within range A1:A3

result = Target.Value ' set result variable equal to whatever the target cell value is

If Not Intersect(Target, Range("A1")) Is Nothing Then 'if cell A1, evaluate cb1

    If InStr(UCase(result), search1P) <> 0 Then 'if result variable contains "1P" then
    ComboBox1.ListFillRange = "Range1" 'Populate cb1 with "Range1"
    ElseIf InStr(UCase(result), search2P) <> 0 Then 'if result variable contains "2P" then
    ComboBox1.ListFillRange = "Range2" 'populate combobox with "Range2"
    Else: ComboBox1.ListFillRange = "" 'leave cb blank if source cell is invalid
    End If

ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then 'if cell A2, update cb2

    If InStr(UCase(result), search1P) <> 0 Then 'if result variable contains "1P" then
    ComboBox2.ListFillRange = "Range1" 'Populate cb1 with "Range1"
    ElseIf InStr(UCase(result), search2P) <> 0 Then 'if result variable contains "2P" then
    ComboBox2.ListFillRange = "Range2" 'populate combobox with "Range2"
    Else: ComboBox2.ListFillRange = "" 'leave cb blank if source cell is invalid
    End If

ElseIf Not Intersect(Target, Range("A3")) Is Nothing Then 'if cell A2, update cb3

    If InStr(UCase(result), search1P) <> 0 Then 'if result variable contains "1P" then
    ComboBox3.ListFillRange = "Range1" 'Populate cb1 with "Range1"
    ElseIf InStr(UCase(result), search2P) <> 0 Then 'if result variable contains "2P" then
    ComboBox3.ListFillRange = "Range2" 'populate combobox with "Range2"
    Else: ComboBox3.ListFillRange = "" 'leave cb blank if source cell is invalid
    End If

End If

End If

End Sub