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

Excel VBA复制动态单元格区域时未复制全部值如何解决

问题修复方案

核心错误原因

代码中计算单元格范围时未明确绑定所属工作表,Range默认调用当前激活工作表的属性,无法匹配每个带- Pay标识的源工作表的实际数据行数,导致复制范围异常。

修正后完整代码

Dim ws As Worksheet
Dim targetws As Worksheet
Dim LastRow As Long
Dim TransactionColumn As Variant
Dim targetStartRow As Long

TransactionColumn = "D"
Set targetws = Sheets("targetwsname")

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name Like "* - Pay*" Then
        ' 计算当前源工作表D列最后一行有效数据行号
        LastRow = ws.Cells(ws.Rows.Count, TransactionColumn).End(xlUp).Row
        ' 计算目标表D列的粘贴起始行,要求首次粘贴不早于D13
        targetStartRow = targetws.Cells(targetws.Rows.Count, "D").End(xlUp).Offset(1).Row
        If targetStartRow < 13 Then targetStartRow = 13
        ' 执行复制粘贴
        ws.Range("C4:D" & LastRow).Copy Destination:=targetws.Range("D" & targetStartRow)
    End If
Next ws

调整说明

  • 所有Range、Cells、Rows.Count属性都显式绑定所属工作表,避免默认读取活动工作表数据导致的取值错误
  • 源表最后一行计算逻辑移入工作表遍历循环内,每次针对当前处理的源表计算真实数据结束位置
  • 新增粘贴起始行判断,满足首次粘贴从目标表D13开始的需求,后续追加数据自动顺延到D列第一个空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:51:03