首页 > 解决方案 > 我需要检查目标工作表中是否已经有一行,如果是,我不希望它复制并创建重复项

问题描述

Sub Copy_Amazon()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long
    Dim DestLastRow As Long
    
    Set src = Workbooks("AMZN COMBINED.xlsm").Worksheets("AMZN")
    Set tgt = Workbooks("Archive_Dispatched.xlsx").Worksheets("Amazon")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False
 
    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1 :O" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:O" & lastRow)

    ' filter range based on column J
    filterRange.AutoFilter field:=5, Criteria1:="D"

    ' copy the visible cells to our target range
    DestLastRow = tgt.Cells(tgt.Rows.Count, "A").End(xlUp).Offset(1).Row
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A" & DestLastRow)
    
    'Turn off Auto Filter again
    src.AutoFilterMode = False

End Sub

如问题所述,我可以使用自动过滤器将行从源复制并粘贴到目标工作表,但我试图只引入新行或更改的行,关于我如何做到这一点的任何想法?

标签: excelvba

解决方案


推荐阅读