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

VBA点击按钮添加行异常:新增行出现在顶部而非底部求助

问题排查与修复方案

你的代码核心问题是仅通过A列判断表格最后一行,但实际Sheet1的表格数据最后一行并非A列的最后一行(比如A列存在空行、数据集中在其他列),导致计算出的lastRow远小于真实的表格底部行,最终插入位置偏上。

修复步骤:

  1. 修正最后一行的计算逻辑
    替换原代码中查找A列最后一行的部分,改为查找整个工作表的最后使用行(更准确):

    ' 替换原lastRow的计算代码
    Dim lastRow As Long
    On Error Resume Next ' 处理工作表全空的情况
    lastRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
    On Error GoTo 0
    If lastRow = 0 Then lastRow = 1 ' 全空时默认从第1行后插入
    

    如果你的表格有固定的关键列(比如B列),也可以指定该列来计算:

    lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row ' 替换"B"为你的关键列
    
  2. 优化冗余代码
    原代码中循环15次重复设置Q列的固定文本,完全没必要,把这部分移到循环外只执行一次:

    ' 移到For col = 1 To 15循环之前
    ws.Cells(nextRow, 17).Value = "From Unit"
    ws.Cells(nextRow + 1, 17).Value = "Qty"
    ws.Cells(nextRow + 2, 17).Value = "To Unit"
    ws.Cells(nextRow + 3, 17).Value = "Selling Price"
    
  3. 修复Units表数据读取逻辑
    原代码中unitsRow = nextRow - lastRow + 2会导致每次新增行都读取Units表的第3行数据,如果你想依次读取Units表的行,改成静态变量累计:

    ' 在循环内替换原unitsRow相关代码
    Static currentUnitsRow As Long
    If currentUnitsRow = 0 Then currentUnitsRow = 2 ' 假设Units表数据从第2行开始
    ws.Cells(nextRow, col + 17).Value = unitsSheet.Cells(currentUnitsRow, 1).Value
    currentUnitsRow = currentUnitsRow + 1
    

完整修复后的代码示例:

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim unitsSheet As Worksheet
Set unitsSheet = ThisWorkbook.Sheets("Units")

' 查找工作表最后使用行
Dim lastRow As Long
On Error Resume Next
lastRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
On Error GoTo 0
If lastRow = 0 Then lastRow = 1

Dim nextRow As Long
nextRow = lastRow + 1

' 插入4行
ws.Rows(nextRow).Resize(4).Insert Shift:=xlDown

' 设置Q列固定文本(仅执行一次)
ws.Cells(nextRow, 17).Value = "From Unit"
ws.Cells(nextRow + 1, 17).Value = "Qty"
ws.Cells(nextRow + 2, 17).Value = "To Unit"
ws.Cells(nextRow + 3, 17).Value = "Selling Price"

' 合并A-O列的4行
Dim col As Integer
Static currentUnitsRow As Long
If currentUnitsRow = 0 Then currentUnitsRow = 2 ' 初始化Units表起始行

For col = 1 To 15
    With ws
        .Range(.Cells(nextRow, col), .Cells(nextRow + 3, col)).Merge
    End With
    
    ' 读取Units表数据
    ws.Cells(nextRow, col + 17).Value = unitsSheet.Cells(currentUnitsRow, 1).Value
    currentUnitsRow = currentUnitsRow + 1
Next col

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:30:39