Share via


ListBox 控制項、AddItem、RemoveItem 方法、ListIndex、ListCount 屬性範例

下列範例會使用AddItem 和 RemoveItem方法,以及ListIndexListCount屬性來新增和刪除ListBox的內容。

若要使用本範例,請將此範例程式碼複製到表單的宣告部分中。 請確定表單包含:

  • 一個名為 ListBox1 的 ListBox
  • 兩個分別名為 CommandButton1 和 CommandButton2 的 CommandButton 控制項。
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 支援與意見反應