ListBox コントロール、AddItem メソッド、RemoveItem メソッド、ListIndex プロパティ、ListCount プロパティの例

次の例では、AddItem メソッドと RemoveItem メソッドと ListIndex プロパティと ListCount プロパティを使用して、ListBox の内容を追加および削除します。

この例を使用するには、以下のサンプル コードをフォームの宣言部分にコピーします。 フォームに次が含まれていることを確認してください。

  • リスト ボックス ( ListBox ) コントロール (ListBox1)
  • 2 つのコマンド ボタン ( CommandButton ) コントロール (CommandButton1 と CommandButton2)
Dim EntryCount As Single 
 
Private Sub CommandButton1_Click() 
 EntryCount = EntryCount + 1 
 ListBox1.AddItem (EntryCount & " - Selection") 
End Sub
Private Sub CommandButton2_Click() 
 'Ensure ListBox contains list items 
 If ListBox1.ListCount >= 1 Then 
 'If no selection, choose last list item. 
 If ListBox1.ListIndex = -1 Then 
 ListBox1.ListIndex = _ 
 ListBox1.ListCount - 1 
 End If 
 ListBox1.RemoveItem (ListBox1.ListIndex) 
 End If 
End Sub
Private Sub UserForm_Initialize() 
 EntryCount = 0 
 CommandButton1.Caption = "Add Item" 
 CommandButton2.Caption = "Remove Item" 
End Sub

サポートとフィードバック

Office VBA またはこの説明書に関するご質問やフィードバックがありますか? サポートの受け方およびフィードバックをお寄せいただく方法のガイダンスについては、Office VBA のサポートおよびフィードバックを参照してください。