从多个combobox中删除项目

我有7个combobox。 所有这些combobox具有相同的来源。

With Sheets("Data_Sheet")

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

End With

相同的代码已被写入其他组合。

现在,当从combobx1中select一个值时,它不应该出现在其他的combobox中。 当我尝试用下面的代码来做到这一点,但我得到这个代码的错误。

j = ComboBox1.ListIndex

ComboBox2.RemoveItem (j)

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

这段代码有什么不正确?

RemoveItem方法适用于我,除非我使用.ListFillRange方法来填充combobox。 如果您使用.List方法,它应该工作。 要做到这一点,你必须将范围转换为数组。

修订

感谢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 

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