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

如何让VBA自动插入行并输出内容,且不影响表格其余区域对齐

修改VBA代码实现自动插入空行并输出内容

以下是修改后的代码,可自动在Sheet1第29行插入空行(保持格式对齐),并根据条件在该行B列输出对应内容:

Sub Energy_consumption_per_cubic()
    Dim s1 As Worksheet, s2 As Worksheet
    Dim check1 As Boolean, check12 As Boolean, motor_power As Boolean, flow As Boolean

    Set s1 = ThisWorkbook.Worksheets(1)
    Set s2 = ThisWorkbook.Worksheets(2)
    
    ' 在第29行插入空行,继承上方格式以保持表格对齐
    s1.Rows("29:29").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

    check1 = s2.CheckBoxes("Check Box 1").Value = xlOn
    check12 = s2.CheckBoxes("Check Box 5").Value = xlOn
    motor_power = s1.Range("B25").Value = "Motor Power"
    flow = s1.Range("B26").Value = "Flow(from fill level)"

    If ((check1 And check12) Or _
        (check1 And motor_power) Or _
        (flow And check12) Or _
        (flow And motor_power)) Then
            s1.Range("B29").Value = "Energy consumption per cubic"
    Else
        s1.Range("B29").Value = "-"
    End If
End Sub

关键修改说明

  • 新增行插入逻辑:用Rows("29:29").Insert插入整行,Shift:=xlDown让原29行及以下内容下移;CopyOrigin:=xlFormatFromLeftOrAbove参数确保插入的空行继承上方行的格式,避免破坏表格其余区域的对齐效果。
  • 插入空行后,新的第29行就是目标行,后续赋值逻辑直接对B29操作即可,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:39:18