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

VBA跨可变行列复制公式报错(类型不匹配)排查

解决VBA AutoFill运行时错误13(类型不匹配)问题

错误原因分析

你报错的代码行里,Cells("O" & nextfree, lastcolumn) 用错了Cells对象的语法:Cells的参数是**(行号, 列号)**,第一个参数必须是数字类型的行号,而你写的"O" & nextfree是字符串(比如"O15"),无法被识别为有效行号,直接导致类型不匹配错误。

修正方案

把AutoFill的目标范围改成正确的Cells组合写法,同时确保填充方向匹配横向需求:

修正后的关键代码行

Range("O" & nextfree).AutoFill Destination:=Range(Cells(nextfree, "O"), Cells(nextfree, lastcolumn)), Type:=xlFillDefault

完整修正代码示例(适配原有逻辑)

Sub AddSumFormulaAndFill()
    Dim ws As Worksheet
    Dim nextfree As Long
    Dim lastcolumn As Long
    Dim sumStartRow As Long ' 求和起始行,按需调整
    
    ' 指定目标工作表,避免激活表变化出问题
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    sumStartRow = 2 ' 示例:从第2行开始求和
    
    ' 获取O列最后空白行的行号
    nextfree = ws.Cells(ws.Rows.Count, "O").End(xlUp).Row + 1
    
    ' 给O列空白单元格添加上方区域求和公式
    ws.Range("O" & nextfree).Formula = "=SUM(O" & sumStartRow & ":O" & nextfree - 1 & ")"
    
    ' 获取当前数据区域的最后一列列号
    lastcolumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    
    ' 横向自动填充公式
    ws.Range("O" & nextfree).AutoFill _
        Destination:=ws.Range(ws.Cells(nextfree, "O"), ws.Cells(nextfree, lastcolumn)), _
        Type:=xlFillDefault
End Sub

额外提示

  • 求和起始行sumStartRow可根据你的实际数据结构调整
  • 明确指定工作表对象(如ThisWorkbook.Worksheets("Sheet1"))比用ActiveSheet更稳定
  • xlFillDefault会自动识别公式的相对引用规则,横向填充时会自动把列标从O替换为P、Q等,符合跨列求和需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:20:25