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

如何用VBA找出两个订单列表差异并复制对应新增行?

解决VBA提取新增订单号的问题

原代码的问题

  • 变量声明拼写错误:Souce应为Source,会导致编译警告
  • 逻辑方向错误:遍历旧列表无法找出新增订单,应遍历新列表,检查哪些订单不在旧列表中
  • 区域比较错误:c <> Source2.Range("D2:D250")不能直接用单个单元格和整列区域做比较,VBA无法识别这种多值判断
  • 行号匹配错误:Source2.Rows(c.Row)中c是旧列表的单元格,行号和新列表不对应

修正后的代码

测试版(输出到test工作表)

Sub OrderDifferences()
    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet ' 旧订单列表
    Dim Source2 As Worksheet ' 新订单列表
    Dim Target As Worksheet ' 测试输出表
    
    ' 绑定工作表
    Set Source = Worksheets("Open Orders Intern")
    Set Source2 = Worksheets("New Report")
    Set Target = Worksheets("test")
    
    ' 清空测试表原有内容(可选)
    Target.Cells.Clear
    
    j = 1
    ' 遍历新列表的订单号区域(动态获取最后一行,避免固定250行的限制)
    For Each c In Source2.Range("D2:D" & Source2.Cells(Source2.Rows.Count, "D").End(xlUp).Row)
        ' 检查当前订单号是否不在旧列表中
        If IsError(Application.Match(c.Value, Source.Range("D5:D" & Source.Cells(Source.Rows.Count, "D").End(xlUp).Row), 0)) Then
            ' 复制新列表对应整行到测试表
            Source2.Rows(c.Row).Copy Target.Rows(j)
            j = j + 1
        End If
    Next c
End Sub

最终版(直接追加到旧列表末尾)

如果不需要测试表,直接把新增行复制到旧列表最后一行的下方:

Sub AddNewOrdersToOldList()
    Dim c As Range
    Dim lastRowOld As Long
    Dim lastRowNew As Long
    Dim Source As Worksheet
    Dim Source2 As Worksheet
    
    Set Source = Worksheets("Open Orders Intern")
    Set Source2 = Worksheets("New Report")
    
    ' 获取旧列表的最后一行(D列)
    lastRowOld = Source.Cells(Source.Rows.Count, "D").End(xlUp).Row
    ' 获取新列表的最后一行(D列)
    lastRowNew = Source2.Cells(Source2.Rows.Count, "D").End(xlUp).Row
    
    ' 遍历新列表的订单号
    For Each c In Source2.Range("D2:D" & lastRowNew)
        ' 检查订单号是否不在旧列表中
        If IsError(Application.Match(c.Value, Source.Range("D5:D" & lastRowOld), 0)) Then
            lastRowOld = lastRowOld + 1
            ' 复制整行到旧列表末尾
            Source2.Rows(c.Row).Copy Source.Rows(lastRowOld)
        End If
    Next c
End Sub

关键改进点

  • 使用Application.Match函数精准判断订单号是否存在,返回错误值则表示该订单是新增的
  • 动态获取列表最后一行(End(xlUp)),避免固定行号导致遗漏订单或误判空行
  • 修正遍历对象为新列表,确保找出的是新增的订单号
  • 修复变量拼写错误,消除编译问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:55:27