excel vba 查询数据,调用数据源表格形式,使用listbox显示
时间: 2024-06-01 08:14:13 浏览: 34
您好,可以使用以下代码实现您的需求:
Private Sub UserForm_Initialize()
Dim ws As Worksheet
Dim lr As Integer
Set ws = ThisWorkbook.Sheets("数据源") '将数据源改为您的数据源表格名称
lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
ListBox1.ColumnCount = 3 '此处为您的ListBox控件列数
ListBox1.ColumnWidths = "50;100;100" '如果需要设置列宽,可以修改此处
ListBox1.ListHeaderCount = 1 '设置为1表示有表头
ListBox1.List(0, 0) = "ID" '表头名称
ListBox1.List(0, 1) = "姓名"
ListBox1.List(0, 2) = "年龄"
For i = 2 To lr
ListBox1.AddItem '添加新行
ListBox1.List(i - 1, 0) = ws.Cells(i, 1).Value '第一列数据(ID)
ListBox1.List(i - 1, 1) = ws.Cells(i, 2).Value '第二列数据(姓名)
ListBox1.List(i - 1, 2) = ws.Cells(i, 3).Value '第三列数据(年龄)
Next i
End Sub
此代码将数据源工作表中的数据添加到ListBox控件中,您可以根据需要进行修改。