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

在UserForm列表框填充关闭工作簿数据时遇类型不匹配错误求助

解决VBA类型不匹配错误(填充ListBox)

错误原因分析

你的代码存在两个关键问题导致类型不匹配:

  1. ColumnCount赋值逻辑错误:将记录行数rs.RecordCount赋值给列数属性.ColumnCount,但.ColumnCount需要的是查询结果的字段数量,应该用rs.Fields.Count。
  2. 单条/空记录集的数组兼容问题:当查询结果为空时,Transpose会直接报错;当只有1条记录时,rs.GetRows返回的二维数组经Transpose后会变成一维数组,与ListBox要求的二维数组格式不匹配。

修正后的代码

Private Sub UserForm_Initialize()
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim dataArr As Variant
    Dim tempArr As Variant
    Dim i As Integer
    
    Set cn = New ADODB.Connection
    cn.ConnectionString = _
                     "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                     "Data Source=F:\Book1.xlsx;" & _
                     "Extended Properties='Excel 12.0 Xml;HDR=YES';"
    
    cn.Open
    Set rs = New ADODB.Recordset
    rs.Open "select [date] ,[factory] ,[records] from [sheet1$]", cn
    
    With Me.ListBox1
        .ColumnCount = rs.Fields.Count ' 正确设置列数为查询的字段数量
        If Not rs.EOF Then
            dataArr = rs.GetRows
            ' 处理单条记录的情况,确保输出为二维数组
            If UBound(dataArr, 2) = 0 Then
                ReDim tempArr(1 To 1, 1 To rs.Fields.Count)
                For i = 1 To rs.Fields.Count
                    tempArr(1, i) = dataArr(i - 1, 0)
                Next i
                .List = tempArr
            Else
                .List = Application.WorksheetFunction.Transpose(dataArr)
            End If
        Else
            .Clear ' 无数据时清空ListBox
        End If
    End With
    
    rs.Close
    cn.Close
    ' 释放对象避免内存泄漏
    Set rs = Nothing
    Set cn = Nothing
End Sub

关键修正点说明

  • 列数设置修正:用rs.Fields.Count替代rs.RecordCount,匹配你查询的3列数据。
  • 空记录集处理:通过rs.EOF判断是否存在数据,避免空数组引发的错误。
  • 单条记录兼容:手动构建二维数组,解决Transpose返回一维数组导致的类型不匹配。
  • 对象释放:添加对象释放代码,避免长期运行产生内存泄漏问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:09:24