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

多列ListBox设置List属性时报Run-time error '381'求助

解决VBA多列ListBox的Run-time error '381'及数据显示异常问题

错误原因分析

Run-time error '381' 本质是ListBox的行/列索引越界:你直接尝试访问ListBox1.List(1, 0)时,ListBox还没有初始化足够的行数(默认行数为0),导致索引无效。而数据重复、第一行无变化的问题,通常是因为没有清空原有列表就重复填充,或者赋值逻辑错误。

具体解决步骤

  • 先配置ListBox的列属性
    必须确保ListBox的ColumnCount属性与你的数据列数匹配(比如2列就设为2),同时设置ColumnWidths(如"100;100")让列正常显示。可以在属性窗口设置,也可以在代码里初始化:

    ListBox1.ColumnCount = 2
    ListBox1.ColumnWidths = "100;100"
    
  • 避免直接访问未存在的行索引
    不能直接给List(1, 0)赋值,因为此时ListBox没有第二行。正确的填充方式有两种:

    1. 直接绑定二维数组(推荐)
      确保你的数组是二维结构,列数与ListBox的ColumnCount一致,直接赋值给List属性,一次性完成填充:
      ListBox1.Clear ' 先清空原有内容
      ListBox1.List = MyArray
      
    2. 逐行添加并赋值
      先通过AddItem添加行,再通过当前最后一行的索引(ListCount - 1)给列赋值:
      ListBox1.Clear
      For i = LBound(MyArray, 1) To UBound(MyArray, 1)
          ListBox1.AddItem ' 添加一行
          ' 给当前行的第1列(索引0)赋值
          ListBox1.List(ListBox1.ListCount - 1, 0) = MyArray(i, 1)
          ' 给当前行的第2列(索引1)赋值
          ListBox1.List(ListBox1.ListCount - 1, 1) = MyArray(i, 2)
      Next i
      
  • 清空原有列表
    每次填充前调用ListBox1.Clear,避免旧数据残留导致重复显示。

完整示例代码

Sub FillMultiColumnListBox()
    Dim MyArray As Variant
    Dim i As Integer
    
    ' 构造示例二维数组(3行2列)
    MyArray = Range("A1:B3").Value ' 也可以手动构造:Array(Array("a","b"), Array("c","d"), Array("e","f"))
    
    ' 初始化ListBox
    ListBox1.Clear
    ListBox1.ColumnCount = 2
    ListBox1.ColumnWidths = "100;100"
    
    ' 方法1:直接绑定数组
    ListBox1.List = MyArray
    
    ' 方法2:逐行添加(注释掉方法1即可启用)
    ' For i = 1 To UBound(MyArray, 1)
    '     ListBox1.AddItem
    '     ListBox1.List(ListBox1.ListCount - 1, 0) = MyArray(i, 1)
    '     ListBox1.List(ListBox1.ListCount - 1, 1) = MyArray(i, 2)
    ' Next i
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:00:56