詳細講解Listbox控件在窗體中的運用
概述:在我們工作中會遇到會将數據導入到列表框(listbox)的形式來方便數據的查看與查詢。再通過VBA代碼可在Excel中輕松實現數據的查詢和導入。本文以最新發布的“物料管理系統2.0”為例進行講解。
1.1 在窗體中創建列表框
在Excel按Alt F11進入VBA界面,鼠标右擊空白處插入窗體。
1.2 在工具箱選擇列表框控件,并在剛剛新建的窗體中拖動大小到合适位置。
1.3 在工具箱選擇命令按鈕,并在窗體中拖動成查詢按鈕。
1.4 添加數據源(sheet2)的數據到列表框。
1.4.1雙擊“查詢”按鈕,并在按鈕下輸入如下代碼:(下方紅色字體為代碼注釋)
Private Sub CommandButton2_Click()
a = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row
(獲取數據源工作表數據的行數)
If TextBox1 = "" Then Sheet2.Range("b1") = ""
ListBox1.Clear (清空列表框的内容)
ListBox1.ColumnWidths = "120;90;150;50;50;90;50;70;80" (列表框每列的寬度)
ListBox1.ColumnCount = 9 (列表框的列數)
ListBox1.AddItem Sheet2.Cells(2, 1).Value
ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet2.Cells(2, 2).Value
ListBox1.List(ListBox1.ListCount - 1, 2) = Sheet2.Cells(2, 3).Value
ListBox1.List(ListBox1.ListCount - 1, 3) = Sheet2.Cells(2, 4).Value
ListBox1.List(ListBox1.ListCount - 1, 4) = Sheet2.Cells(2, 5).Text
ListBox1.List(ListBox1.ListCount - 1, 5) = Sheet2.Cells(2, 6).Value
ListBox1.List(ListBox1.ListCount - 1, 6) = Sheet2.Cells(2, 7).Value
ListBox1.List(ListBox1.ListCount - 1, 7) = Sheet2.Cells(2, 8).Value
ListBox1.List(ListBox1.ListCount - 1, 8) = Sheet2.Cells(2, 9).Value
(以上代碼為将數據源第二行的數據分别添加到列表框)
For i = 3 To a
If Sheet2.Cells(i, 10) = 1 Then
ListBox1.AddItem Sheet2.Cells(i, 1).Value
ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet2.Cells(i, 2).Value
ListBox1.List(ListBox1.ListCount - 1, 2) = Sheet2.Cells(i, 3).Value
ListBox1.List(ListBox1.ListCount - 1, 3) = Sheet2.Cells(i, 4).Value
ListBox1.List(ListBox1.ListCount - 1, 4) = Sheet2.Cells(i, 5).Text
ListBox1.List(ListBox1.ListCount - 1, 5) = Sheet2.Cells(i, 6).Value
ListBox1.List(ListBox1.ListCount - 1, 6) = Sheet2.Cells(i, 7).Value
ListBox1.List(ListBox1.ListCount - 1, 7) = Sheet2.Cells(i, 8).Value
ListBox1.List(ListBox1.ListCount - 1, 8) = Sheet2.Cells(i, 9).Value
End If
Next
(以上代碼為将數據源第三行到最後有數據一行的數據分别添加到列表框。)
End Sub
1.5 模糊查詢:模糊查詢這裡主要是通過search函數判斷物料編碼是否含有輸入的字符。如下如所示,在查詢的輔助列輸入函數“=IFERROR(IF(SEARCH($B$1,[@物料編碼])>0,1,0),0)”函數的大概意思就是在查詢框輸入内容後,判斷輸入内容在物料編碼列返回的位置。
1.6 代碼中Sheet2.Cells(i, 10) = 1為判斷輸入字符是否在物料編碼中存在
1.7 實現效果見下圖,自動顯示物料編碼中含有“33”的物料。
結語:本期教程就分享到這裡,有疑問可在評論區留言,小編看到後會及時回複。如果對你有幫助可點贊留言支持。
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!