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

Excel VBA:如何选取DataBodyRange第2行至末行并设置不同公式?

解决方法

你的核心问题是引用范围时的对象归属错误,原代码里的.Cells(2)和.Cells(.DataBodyRange.Rows.Count)指向的是With块中的ListObject,而非ListColumn(9).DataBodyRange,导致范围选取失败。以下是两种简洁的实现方式,无需循环:

方法1:使用Offset+Resize

通过Offset(1)跳过首行,再用Resize调整范围到剩余行数:

With ActiveSheet.ListObjects("disp_plan")
    ' 设置第9列首行公式
    .DataBodyRange.Cells(1, 9).Formula = "=R17C17+R3C2"
    ' 设置第9列第2行到最后一行的公式
    .ListColumn(9).DataBodyRange.Offset(1).Resize(.ListColumn(9).DataBodyRange.Rows.Count - 1).FormulaR1C1 = "=R[-1]C+RC[-2]"
End With

方法2:直接定位DataBodyRange的行范围

通过Rows属性直接选取第2行至最后一行,再指定第9列:

With ActiveSheet.ListObjects("disp_plan")
    .DataBodyRange.Cells(1, 9).Formula = "=R17C17+R3C2"
    .DataBodyRange.Rows("2:" & .DataBodyRange.Rows.Count).Columns(9).FormulaR1C1 = "=R[-1]C+RC[-2]"
End With

补充说明

  • 两种方法都直接操作单元格区域,效率远高于循环;
  • 如果动态表格可能为空(DataBodyRange不存在),建议先判断Not .DataBodyRange Is Nothing,避免运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:01:27