Excel VBA搜索工作表时如何将多列数据填充至ListBox
解决Excel VBA搜索B列后同步填充A、C列数据到ListBox的问题
你的代码目前仅添加了匹配行B列的内容,要同时显示A、C列数据,需先配置ListBox的多列属性,再在循环中获取同一行的A、C列数据并填充到对应列。
修改后的完整代码
Dim iSheet As Worksheet Dim iBook As Workbook Set iBook = Application.ThisWorkbook Set iSheet = iBook.Sheets("Bin13In") Dim foundCell As Range Dim firstAddress As String Me.ListBox1.Clear ' 设置ListBox为3列,定义列宽(可按需调整) Me.ListBox1.ColumnCount = 3 Me.ListBox1.ColumnWidths = "80,80,80" ' 列宽单位为磅 With iSheet.Range("B1:B14000") Set foundCell = .Find(TextBox5.Text, LookIn:=xlValues, LookAt:=xlPart) If Not foundCell Is Nothing Then firstAddress = foundCell.Address Do ' 添加A列数据作为第一列 Me.ListBox1.AddItem foundCell.Offset(0, -1).Text ' 设置第二列为B列匹配内容 Me.ListBox1.List(Me.ListBox1.ListCount - 1, 1) = foundCell.Text ' 设置第三列为C列数据 Me.ListBox1.List(Me.ListBox1.ListCount - 1, 2) = foundCell.Offset(0, 1).Text Set foundCell = .FindNext(foundCell) Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress Else MsgBox "Not found" End If End With
关键改动说明
配置ListBox多列属性:
ColumnCount = 3:指定ListBox显示3列(对应A、B、C列)ColumnWidths:自定义每列宽度,数值可根据实际需求调整
获取同行A、C列数据:
- 用
foundCell.Offset(0, -1)定位当前匹配B列单元格左侧的A列单元格 - 用
foundCell.Offset(0, 1)定位当前匹配B列单元格右侧的C列单元格 - 通过
ListBox1.List(行索引, 列索引)设置对应列内容,ListCount - 1指向刚添加的行
- 用
变量名优化:将原变量
A改为foundCell,提升代码可读性(可选但推荐)
内容的提问来源于stack exchange,提问作者CSM71593
相关产品推荐
相关产品推荐

