从多个组合框中删除项目

时间:2013-09-14 20:30:36

标签: excel vba excel-vba combobox

我有7个组合框。所有这些组合框都有相同的来源。

With Sheets("Data_Sheet")

Sheets("UI_Interface").ComboBox2.ListFillRange = "Data_Sheet!E2:E" & .Cells(Rows.Count, 5).End(xlUp).Row

End With

已为其他组合框编写了相同的代码。

现在,当选择了来自combobx1的值时,它不应出现在其他组合框中。 当我尝试使用以下代码执行此操作时,但我收到此代码的错误。

j = ComboBox1.ListIndex

ComboBox2.RemoveItem (j)

我尝试了一些不同的属性来删除值,但都有一些例外。

此代码中有什么不正确?

1 个答案:

答案 0 :(得分:3)

除非我使用RemoveItem方法填充组合框,否则.ListFillRange方法适合我。如果您使用.List方法,它应该可以工作。为此,您必须将范围转换为数组。

<强> REVISED

感谢enderland指出您正在使用工作表上的表单控件,而不是用户表单。因此,该方法应该类似,但您将无法使用ListFillRange方法。没什么大不了的,我们可以轻松地获取该范围,将其转换为变体/数组,并使用List方法。

Option Explicit
Private Sub Worksheet_Activate()
'## Sets default list for ComboBoxes on this sheet
    SetComboBoxLists ComboBox1
    SetComboBoxLists ComboBox2

End Sub
Private Sub ComboBox1_Change()
'## event handler for a combobox, repeat as needed
    '## Repopulate the list, otherwise you may get
    '    an Index out of Range error or Invalid Argument error,
    '    or the RemoveItem method will remove the wrong item
    SetComboBoxList ComboBox2
    '## Now, remove the item selected in ComboBox1
    ComboBox2.RemoveItem ComboBox1.ListIndex
End Sub

Private Sub SetComboBoxLists(cBox As MSForms.ComboBox)
'## Subroutine to fill the list in each combobox as needed
Dim lstRange As Variant

    '## Populate the array variable to use for the combobox.List method:
    '    double-check that I put the parentheses in the right place!
    With Sheets("Data_Sheet")
        lstRange = .Range("E2:E" & .Cells(Rows.Count, 5).End(xlUp).Row)
    End With

    '## Populate the combobox with the list
    cBox.List = lstRange

End Sub

请注意,如果您的任何代码操作(例如,调整大小,删除行等)范围,则需要重新应用List方法。

相关问题