You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键改动说明

  1. 配置ListBox多列属性:

    • ColumnCount = 3:指定ListBox显示3列(对应A、B、C列)
    • ColumnWidths:自定义每列宽度,数值可根据实际需求调整
  2. 获取同行A、C列数据:

    • 用foundCell.Offset(0, -1)定位当前匹配B列单元格左侧的A列单元格
    • 用foundCell.Offset(0, 1)定位当前匹配B列单元格右侧的C列单元格
    • 通过ListBox1.List(行索引, 列索引)设置对应列内容,ListCount - 1指向刚添加的行
  3. 变量名优化:将原变量A改为foundCell,提升代码可读性(可选但推荐)

内容的提问来源于stack exchange,提问作者CSM71593

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:45:38