VBA从2个条件的2个excel文件中复制

时间:2016-06-10 08:48:01

标签: excel vba excel-vba

我想将source.xlsm中A列上的名称复制到destination.xlsm ONLY如果名称不存在,如果它不存在则应该写在destination.xlsm列的末尾。

我不知道如何继续代码

Podfile

1 个答案:

答案 0 :(得分:2)

我已添加评论来解释此代码中发生的情况 - 如果您不确定其中任何内容只是评论......

Sub Recopy()
Dim sourceWb As Workbook
Dim sourceSheet As Worksheet
Dim destWb As Workbook
Dim destLast As Integer
Dim destSheet As Worksheet
dim Lastlign as integer 
dim myLoop as Integer
'## Open both workbooks
Set sourceWb = Workbooks.Open("P:\Desktop\Source.xlsm")
Set sourceSheet = sourceWb.Worksheets("Sheet name in here")
Set destWb = Workbooks.Open(" P:\Desktop\Destination.xlsm")
Set destSheet = destWb.Worksheets("Sheet name in here")

' get the last line of the source sheet so we know how many rows to loop over
Lastlign = sourceSheet.Cells(sourceSheet.Rows.Count, 1).End(xlUp).Row

For myLoop = 1 to Lastlign ' start from 2 if you have a header in row 1
    sourceVal = sourceSheet.Range("A" & myLoop).Value
    With destSheet.Range("A:A")
        Set oFound = .Find(sourceVal)
        If oFound Is Nothing Then
           ' didn't locate the value in col A of destSheet
           ' find last populated row in destination sheet and add 1 for first empty row
           destLast = destSheet.Cells(destSheet.Rows.Count, 1).End(xlUp).Row + 1
           ' set value in destination sheet
           destSheet.Range("A" & destLast).Value = sourceVal 
        End If
    End With
Next

End Sub