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

VBA给指定列自动填充公式报运行时错误1004如何解决

错误原因
  • AutoFill的destination参数格式错误:你当前只传入了最后一行的单元格作为目标范围,但AutoFill要求目标范围必须包含填充起始单元格,也就是需要覆盖从第2行到usedRows1行的整段列范围,不能只写结束单元格。
  • 未显式指定Range所属工作表:代码中Range(usedRows1, emptycolumn)没有绑定工作表对象,默认调用活动工作表的Range,如果执行代码时当前活动表不是Sheet1,就会触发1004错误。
  • 变量usedRows1未提前声明,存在隐式变体变量的风险,可能引发不可预期的错误。
修正后的完整代码
Sub paste_Formula()
    ' 强制变量声明,提前捕获变量未定义问题
    Option Explicit
    
    Dim emptycolumn As Long
    Dim usedRows1 As Long
    Dim destination2 As Worksheet
    
    Set destination2 = Sheets("Sheet1")
    
    With destination2
        ' 统计A列已使用行数
        usedRows1 = .Cells(.Rows.Count, "A").End(xlUp).Row
        ' 定位最后一个空列
        emptycolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        If emptycolumn > 1 Then
            emptycolumn = emptycolumn + 1
        End If
        
        ' 写入表头和首行公式
        .Cells(1, emptycolumn).Value = "Formula"
        .Cells(2, emptycolumn).Formula = "=L2&M2" ' 建议用Formula属性明确写入公式
        
        ' 自动填充,目标范围包含起始单元格到A列最后一行
        .Cells(2, emptycolumn).AutoFill _
            Destination:=.Range(.Cells(2, emptycolumn), .Cells(usedRows1, emptycolumn)), _
            Type:=xlFillDefault
    End With
End Sub
关键修改说明
  • 调整了AutoFill的目标范围写法:明确指定范围为从第2行的公式起始单元格到A列最后一行的同列单元格,符合AutoFill的参数要求。
  • 所有单元格/范围对象都绑定了destination2工作表对象,避免活动表不匹配导致的错误。
  • 新增Option Explicit强制变量声明,补充了usedRows1的显式声明。
  • 写入公式时改用Formula属性,语义更明确,避免部分场景下把公式识别为普通文本的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:15:03