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

如何在非目标工作表运行宏并解决Range激活失败错误

解决VBA宏激活非活动工作表报错问题

错误原因

原代码依赖.Activate和Selection操作,这类操作要求目标工作表处于活动状态。当“Tool Database”未被选中时,尝试激活该表内单元格会触发运行时错误1004。解决核心是完全规避激活/选择操作,直接通过工作表对象操作单元格范围。

修改后的完整代码

Sub MacroB()
    Dim Output_Sh As Worksheet
    Dim lRow As Long ' A列最后一行(填充目标基准行)
    Dim lastRowE As Long, lastRowF As Long, lastRowG As Long, lastRowH As Long
    
    Set Output_Sh = ThisWorkbook.Sheets("Tool Database")
    
    ' 一次性获取A列最后行,作为所有列的填充目标行
    lRow = Output_Sh.Range("A" & Output_Sh.Rows.Count).End(xlUp).Row
    
    ' 自动填充E列
    lastRowE = Output_Sh.Range("E" & Output_Sh.Rows.Count).End(xlUp).Row
    If lastRowE < lRow Then
        Output_Sh.Range("E" & lastRowE).AutoFill _
            Destination:=Output_Sh.Range("E" & lastRowE & ":E" & lRow)
    End If
    
    ' 自动填充F列
    lastRowF = Output_Sh.Range("F" & Output_Sh.Rows.Count).End(xlUp).Row
    If lastRowF < lRow Then
        Output_Sh.Range("F" & lastRowF).AutoFill _
            Destination:=Output_Sh.Range("F" & lastRowF & ":F" & lRow)
    End If
    
    ' 自动填充G列
    lastRowG = Output_Sh.Range("G" & Output_Sh.Rows.Count).End(xlUp).Row
    If lastRowG < lRow Then
        Output_Sh.Range("G" & lastRowG).AutoFill _
            Destination:=Output_Sh.Range("G" & lastRowG & ":G" & lRow)
    End If
    
    ' 自动填充H列(指定xlFillCopy类型)
    lastRowH = Output_Sh.Range("H" & Output_Sh.Rows.Count).End(xlUp).Row
    If lastRowH < lRow Then
        Output_Sh.Range("H" & lastRowH).AutoFill _
            Destination:=Output_Sh.Range("H" & lastRowH & ":H" & lRow), _
            Type:=xlFillCopy
    End If
End Sub

关键修改说明

  1. 移除激活/选择操作:直接通过Output_Sh.Range(...)引用单元格,无需激活工作表即可完成操作
  2. 优化行号计算:提前获取A列最后行号,避免重复执行End(xlUp),提升代码效率
  3. 变量清晰化:为每列单独定义最后行变量,避免原代码中变量复用导致的逻辑混乱
  4. 增加边界判断:当列数据长度已经和A列一致时,跳过填充操作,避免无意义执行或潜在报错
  5. 明确填充范围:直接指定AutoFill的源单元格和目标范围,无需依赖ActiveCell

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:43:17