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

如何在Excel VBA中定位数据末行后批量添加内容至F列

问题描述

我制作了用于格式化原始数据的电子表格,需在找到数据最后一行后,在F列依次插入以下内容:

TOTALS
YTD Dividends
(空行)
YTD Interest
(空行)
YTD Gain/Loss

目前已通过以下VBA代码实现添加"TOTALS",但不知如何添加后续标题。因每个表格行数不固定,需动态定位末尾行,请问该如何实现?

原代码片段:

'...
End With
    Dim lastrow As Long
    lastrow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row + 2
    With Selection
    ActiveSheet.Cells(lastrow, "F").Value = "TOTALS"
    End With
End Sub
解决方案

你可以基于已获取的lastrow,按顺序给后续行赋值,直接通过行号递增实现,无需额外定位。修改后的代码如下:

'...
End With
    Dim lastrow As Long
    ' 获取D列最后一行数据的行号,再加2作为TOTALS的起始行
    lastrow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row + 2
    
    ' 依次写入需要的内容
    ActiveSheet.Cells(lastrow, "F").Value = "TOTALS"
    ActiveSheet.Cells(lastrow + 1, "F").Value = "YTD Dividends"
    ' 空行无需赋值,直接跳过一行
    ActiveSheet.Cells(lastrow + 3, "F").Value = "YTD Interest"
    ' 再跳过一行
    ActiveSheet.Cells(lastrow + 5, "F").Value = "YTD Gain/Loss"
End Sub

代码说明

  • 以lastrow为起始行,后续内容通过lastrow + n的方式定位行号,n根据行间距调整:
    • lastrow → TOTALS
    • lastrow + 1 → YTD Dividends
    • lastrow + 2 留空(无需赋值)
    • lastrow + 3 → YTD Interest
    • lastrow + 4 留空
    • lastrow + 5 → YTD Gain/Loss
  • 该方式完全基于动态获取的最后一行,无论表格行数如何变化,都能准确插入到数据末尾的指定位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:20:26