You need to enable JavaScript to run this app. VBA从外部工作簿仅更新存量指定列、插入新增行的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

VBA从外部工作簿仅更新存量指定列、插入新增行的实现问题

需求说明

更明确的编辑说明:
假设有两个工作簿A和B,其中B由外部程序导出为.xlsx格式,无法修改。

  1. 第一周,我使用工作簿B中的数据更新工作簿A。
    步骤1完成后工作簿A的状态
  2. 第一周工作期间,我在工作簿A中手动填写“项”列的数据。
    步骤2完成后工作簿A的状态
  3. 我再次使用工作簿B的数据更新工作簿A,但此时注意到部分行的位置发生变化(绿色标记行)、部分内容存在修改,还有部分为全新行。
    步骤3完成后工作簿A的预期状态
    以下是我当前使用的代码:
Sub Update()

Dim lastRowScr As Integer, lastRowLocal As Integer, nRowsSrc As Integer, nRowsLocal As Integer, x As Integer, _
y As Integer

    Application.ScreenUpdating = False
    
       Set closedBook = Workbooks.Open("C:\Users\mfortesg\Documents\Suivi d'Analyses AT\Projet - Automatisation\BO\BO.xlsx")
       
       lastRowScr = closedBook.Sheets(1).Cells.Find(What:="*", SearchDirection:=xlPrevious).Row - 2
       nRowsScr = lastRowScr - 16
       
       lastRowLocal = ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells.Find(What:="*", SearchDirection:=xlPrevious).Row
       nRowsLocal = lastRowLocal - 2
       
       If nRowsLocal = 0 Then
       
            For x = 17 To lastRowScr
            
                y = x - 14
                        
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 1).Value = closedBook.Sheets(1).Cells(x, 1).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 2).Value = closedBook.Sheets(1).Cells(x, 2).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 3).Value = closedBook.Sheets(1).Cells(x, 3).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 4).Value = closedBook.Sheets(1).Cells(x, 4).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 5).Value = closedBook.Sheets(1).Cells(x, 17).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 6).Value = closedBook.Sheets(1).Cells(x, 11).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 7).Value = closedBook.Sheets(1).Cells(x, 10).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 8).Value = closedBook.Sheets(1).Cells(x, 26).Value
                ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 24).Value = Replace(closedBook.Sheets(1).Cells(x, 28).Value, ",", ":")
            
            Next x
            
            MsgBox ("Le Tableau d'Analyse AT a été mis à jour correctement.")
        
            Else
            
            For x = 17 To lastRowScr
    
                For y = x - 14 To lastRowLocal + 1
                    
                    If ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 1).Value = closedBook.Sheets(1).Cells(x, 1).Value And _
                       ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 2).Value = closedBook.Sheets(1).Cells(x, 2).Value And _
                       ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 24).Value = Replace(closedBook.Sheets(1).Cells(x, 28).Value, ",", ":") Then
                    
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 6).Value = closedBook.Sheets(1).Cells(x, 11).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(y, 5).Value = closedBook.Sheets(1).Cells(x, 17).Value
                        
                    ElseIf y = lastRowLocal + 1 Then
                                    
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 1).Value = closedBook.Sheets(1).Cells(x, 1).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 2).Value = closedBook.Sheets(1).Cells(x, 2).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 3).Value = closedBook.Sheets(1).Cells(x, 3).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 4).Value = closedBook.Sheets(1).Cells(x, 4).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 5).Value = closedBook.Sheets(1).Cells(x, 17).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 6).Value = closedBook.Sheets(1).Cells(x, 11).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 7).Value = closedBook.Sheets(1).Cells(x, 10).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 8).Value = closedBook.Sheets(1).Cells(x, 26).Value
                        ThisWorkbook.Sheets("Tableau d'Analyse AT").Cells(x - 14, 24).Value = Replace(closedBook.Sheets(1).Cells(x, 28).Value, ",", ":")
                    
                    End If
                    
                Next y
            
            Next x
            
            MsgBox ("Le Tableau d'Analyse AT a été mis à jour correctement.")
        
        End If
            
       closedBook.Close SaveChanges:=False

     
    Application.ScreenUpdating = True

End Sub

现有代码问题

  • 同步范围不全:更新已有行时仅覆盖A表第5、6列,B中修改的其他同步列(1-4、7、8、24列)不会同步到A,导致数据不一致
  • 新增行逻辑错误:匹配失败时直接写入按B行号计算的x-14行,会覆盖A表中已有的手动填写数据,而非追加到A表末尾
  • 行错位适配缺失:完全依赖按顺序遍历匹配,B中行顺序变动后会出现大量匹配失败、数据错写
  • 未声明对象变量:closedBook未提前定义,易引发类型错误
  • 数值范围风险:行号变量使用Integer类型,数据量超过3万行时会溢出

修正后代码

修正逻辑为:用B表的唯一匹配键构建字典,遍历A表现有行匹配后同步指定列、保留手动填写内容,B表中新增的行追加到A表末尾,不受行顺序变动影响。

Sub Update()
' 声明变量
Dim closedBook As Workbook
Dim wsSrc As Worksheet, wsLocal As Worksheet
Dim lastRowScr As Long, lastRowLocal As Long
Dim srcRow As Long, localRow As Long, nextLocalRow As Long
Dim dict As Object
Dim matchKey As String
Dim srcCol1 As Variant, srcCol2 As Variant, srcCol28 As Variant

' 关闭屏幕刷新提升速度
Application.ScreenUpdating = False
Application.EnableEvents = False

' 绑定源工作表和本地工作表
Set closedBook = Workbooks.Open("C:\Users\mfortesg\Documents\Suivi d'Analyses AT\Projet - Automatisation\BO\BO.xlsx")
Set wsSrc = closedBook.Sheets(1)
Set wsLocal = ThisWorkbook.Sheets("Tableau d'Analyse AT")

' 获取有效行号
lastRowScr = wsSrc.Cells.Find(What:="*", SearchDirection:=xlPrevious).Row - 2
lastRowLocal = wsLocal.Cells.Find(What:="*", SearchDirection:=xlPrevious).Row
nextLocalRow = lastRowLocal + 1

' 创建字典存储源数据的匹配键和行数据
Set dict = CreateObject("Scripting.Dictionary")

' 遍历源表数据,构建字典
For srcRow = 17 To lastRowScr
    ' 构建匹配键:1列值 + 2列值 + 28列值替换逗号为冒号后的结果
    srcCol1 = wsSrc.Cells(srcRow, 1).Value
    srcCol2 = wsSrc.Cells(srcRow, 2).Value
    srcCol28 = Replace(wsSrc.Cells(srcRow, 28).Value, ",", ":")
    matchKey = CStr(srcCol1) & "||" & CStr(srcCol2) & "||" & CStr(srcCol28)
    
    ' 存储该行所有需要同步的源字段
    dict(matchKey) = Array( _
        wsSrc.Cells(srcRow, 1).Value, _
        wsSrc.Cells(srcRow, 2).Value, _
        wsSrc.Cells(srcRow, 3).Value, _
        wsSrc.Cells(srcRow, 4).Value, _
        wsSrc.Cells(srcRow, 17).Value, _
        wsSrc.Cells(srcRow, 11).Value, _
        wsSrc.Cells(srcRow, 10).Value, _
        wsSrc.Cells(srcRow, 26).Value, _
        srcCol28 _
    )
Next srcRow

' 遍历本地表现有行,匹配同步
For localRow = 3 To lastRowLocal ' 从第3行开始为数据行,根据实际表头位置调整
    ' 生成本地行的匹配键
    srcCol1 = wsLocal.Cells(localRow, 1).Value
    srcCol2 = wsLocal.Cells(localRow, 2).Value
    srcCol28 = wsLocal.Cells(localRow, 24).Value
    matchKey = CStr(srcCol1) & "||" & CStr(srcCol2) & "||" & CStr(srcCol28)
    
    ' 匹配到源数据则同步,否则保留原有行
    If dict.Exists(matchKey) Then
        ' 仅同步需要从B获取的列,手动填写的列不会被覆盖
        wsLocal.Cells(localRow, 1).Value = dict(matchKey)(0)
        wsLocal.Cells(localRow, 2).Value = dict(matchKey)(1)
        wsLocal.Cells(localRow, 3).Value = dict(matchKey)(2)
        wsLocal.Cells(localRow, 4).Value = dict(matchKey)(3)
        wsLocal.Cells(localRow, 5).Value = dict(matchKey)(4)
        wsLocal.Cells(localRow, 6).Value = dict(matchKey)(5)
        wsLocal.Cells(localRow, 7).Value = dict(matchKey)(6)
        wsLocal.Cells(localRow, 8).Value = dict(matchKey)(7)
        wsLocal.Cells(localRow, 24).Value = dict(matchKey)(8)
        ' 从字典中移除已匹配的项,剩余的就是新增行
        dict.Remove matchKey
    End If
Next localRow

' 遍历字典剩余项,追加新增行到本地表末尾
For Each matchKey In dict.Keys
    wsLocal.Cells(nextLocalRow, 1).Value = dict(matchKey)(0)
    wsLocal.Cells(nextLocalRow, 2).Value = dict(matchKey)(1)
    wsLocal.Cells(nextLocalRow, 3).Value = dict(matchKey)(2)
    wsLocal.Cells(nextLocalRow, 4).Value = dict(matchKey)(3)
    wsLocal.Cells(nextLocalRow, 5).Value = dict(matchKey)(4)
    wsLocal.Cells(nextLocalRow, 6).Value = dict(matchKey)(5)
    wsLocal.Cells(nextLocalRow, 7).Value = dict(matchKey)(6)
    wsLocal.Cells(nextLocalRow, 8).Value = dict(matchKey)(7)
    wsLocal.Cells(nextLocalRow, 24).Value = dict(matchKey)(8)
    nextLocalRow = nextLocalRow + 1
Next matchKey

' 关闭源工作簿
closedBook.Close SaveChanges:=False

' 恢复设置
Application.ScreenUpdating = True
Application.EnableEvents = True

MsgBox "Le Tableau d'Analyse AT a été mis à jour correctement."

End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 23:36:02