メソッドを使用してコンボボックスにデータを入力しない限り、この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
。