在使用Excel編寫VBA程序時,用到ListBox,然后研究了下它的所有屬性。其實這個控件功能很不好用,太老了,最重要的是還不支持鼠標滾輪,很不好操作,但是考慮到兼容性,還是使用它。
其實讀取、寫入數據用ListBox.List已經足夠了,而BoundColumn和TextColumn主要是用於讀取數據,有什么鳥用?我也不是很清楚,但是可以像下面這樣用。這兩個參數相當於設置了列的索引(j),只需選中行(i)即可讀取對應的數據List(i,j)。其中,BoundColumn與Value關聯;TextColumn與Text關聯。
Private Sub CommandButton1_Click() ListBox1.ListIndex = 0 '選中第一行,不選中的話,讀取不到數值,
ListBox1.BoundColumn = 2 '該屬性從1開始計數,即現在對應的列索引為1;默認值為1
ListBox1.TextColumn = 3 '該屬性從1開始計數,即現在對應的列索引為2;默認值為-1,如果不賦值將無法讀取數據
Debug.Print "value = " & ListBox1.Value '輸出 value = 0,1
Debug.Print "text = " & ListBox1.Text '輸出 text = 0,2
End Sub
Private Sub UserForm_Initialize() Dim i As Integer
Dim j As Integer ListBox1.ColumnCount = 5 '設置5列
i = 0
While i < 10 ListBox1.AddItem j = 0
While j < ListBox1.ColumnCount ListBox1.List(i, j) = CStr(i) & "," & CStr(j) j = j + 1 Wend i = i + 1 Wend End Sub
關鍵詞:VBA ListBox BoundColumn TextColumn Value Text 說明 參數 使用方法 Excel
