MultiSelect、Selected 属性示例MultiSelect, Selected properties example

下面的示例使用多**** 和**所选** 属性演示用户如何在**ListBox** 中选择一个或多个项目。The following example uses the MultiSelect and Selected properties to demonstrate how the user can select one or more items in a ListBox.

用户通过选择选项按钮指定选择方法, 然后从ListBox中选择项。The user specifies a selection method by choosing an option button, and then selects an item(s) from the ListBox. 用户可以通过单击**命令按钮, 在第二个ListBox**中显示所选的项目。The user can display the selected items in a second ListBox by clicking the CommandButton.

若要使用此示例,请将此示例代码复制到窗体的 Declarations 部分。To use this example, copy this sample code to the Declarations portion of a form. 确保该窗体包含:Make sure that the form contains:

  • 两个分别名为"ListBox1"和"ListBox2"的 ListBox 控件。Two ListBox controls named ListBox1 and ListBox2.
  • 一个名为"CommandButton1"的 CommandButtonA CommandButton named CommandButton1.
  • 三个名称分别为"OptionButton1"到"OptionButton3"的 OptionButton 控件。Three OptionButton controls named OptionButton1 through OptionButton3.
Dim i As Integer 
 
Private Sub CommandButton1_Click() 
 ListBox2.Clear 
 
 For i = 0 To 9 
 If ListBox1.Selected(i) = True Then 
 ListBox2.AddItem ListBox1.List(i) 
 End If 
 Next i 
 
End Sub 
 
Private Sub OptionButton1_Click() 
 ListBox1.MultiSelect = fmMultiSelectSingle 
End Sub 
 
Private Sub OptionButton2_Click() 
 ListBox1.MultiSelect = fmMultiSelectMulti 
End Sub 
 
Private Sub OptionButton3_Click() 
 ListBox1.MultiSelect = fmMultiSelectExtended 
End Sub 
 
Private Sub UserForm_Initialize() 
 For i = 0 To 9 
 ListBox1.AddItem "Choice " & (ListBox1.ListCount + 1) 
 Next i 
 
 OptionButton1.Caption = "Single Selection" 
 ListBox1.MultiSelect = fmMultiSelectSingle 
 OptionButton1.Value = True 
 
 OptionButton2.Caption = "Multiple Selection" 
 OptionButton3.Caption = "Extended Selection" 
 
 CommandButton1.Caption = "Show selections" 
 CommandButton1.AutoSize = True 
End Sub

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.