RemoveItem
除非我使用该.ListFillRange
方法填充组合框,否则该方法对我来说正常工作。如果您改用该.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
请注意,如果您的任何代码操作(例如,调整大小、删除行等)该范围,您将需要重新应用该List
方法。