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

如何在Excel宏新增的单元格I7中自动插入公式?

在Excel宏插入的新行中自动添加公式

问题背景

现有如下Excel宏,当在H7单元格输入内容时,会在H7所在行上方插入一行,并选中A7单元格:

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo enditall
    Application.EnableEvents = False
    If Target.Cells.Column = 8 Then
        If Target.Cells.Row = 7 Then
            N = Target.Cells.Row
            If Range("H" & 7).Value <> "" Then
             Range("H7").EntireRow.Insert
             Range("A7").Select
             End If
        End If
    End If
    
enditall:
    Application.EnableEvents = True
End Sub

需要在新增的行中,让新的I7单元格自动应用指定公式,且不能破坏文档其他内容。

修改后的宏代码

直接在插入行的逻辑后添加设置公式的语句即可,以下是完整修改后的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo enditall
    Application.EnableEvents = False
    If Target.Cells.Column = 8 Then
        If Target.Cells.Row = 7 Then
            If Range("H7").Value <> "" Then
                Range("H7").EntireRow.Insert
                ' 给新插入行的I7设置公式,替换成你实际需要的公式内容
                Range("I7").Formula = "=H7*2"
                Range("A7").Select
            End If
        End If
    End If
    
enditall:
    Application.EnableEvents = True
End Sub

关键说明

  • 把代码中的=H7*2替换为你实际需要的公式,比如=SUM(A7:G7)、=VLOOKUP(H7,Sheet2!A:B,2,FALSE)等,确保公式格式符合Excel要求。
  • 保留原有的Application.EnableEvents开关和错误处理,避免触发循环变更事件,同时保证出错后事件能恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:07:08