Share via


TopIndex 屬性範例

下列範例會識別 ListBox 中顯示的最上層專案,以及 ListBox內具有焦點的專案。 此範例會使用 TopIndex 屬性來識別 ListBox頂端顯示的專案,以及使用 ListIndex 屬性來識別具有焦點的專案。

使用者於 ListBox 中選擇項目。 當使用者選取專案或使用者按一下CommandButton時,會更新 TopIndexListIndex的顯示值。

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

  • 一個名為 Label1 的 Label
  • 一個名為 TextBox1 的 TextBox
  • 一個名為 Label2 的 Label
  • 一個名為 TextBox2 的 TextBox
  • 一個名為 CommandButton1 的 CommandButton
  • 一個名為 ListBox1 的 ListBox
Private Sub CommandButton1_Click() 
 ListBox1.TopIndex = ListBox1.ListIndex 
 TextBox1.Text = ListBox1.TopIndex 
 TextBox2.Text = ListBox1.ListIndex 
End Sub 
 
Private Sub ListBox1_Change() 
 TextBox1.Text = ListBox1.TopIndex 
 TextBox2.Text = ListBox1.ListIndex 
End Sub 
 
Private Sub UserForm_Initialize() 
 Dim i As Integer 
 
 For i = 0 To 24 
 ListBox1.AddItem "Choice " & (i + 1) 
 Next i 
 ListBox1.Height = 66 
 CommandButton1.Caption = "Move to top of list" 
 CommandButton1.AutoSize = True 
 CommandButton1.TakeFocusOnClick = False 
 
 Label1.Caption = "Index of top item" 
 TextBox1.Text = ListBox1.TopIndex 
 
 Label2. Caption = "Index of current item" 
 Label2.AutoSize = True 
 Label2.WordWrap = False 
 TextBox2.Text = ListBox1.ListIndex 
End Sub

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應