在工作表之间复制和粘贴行

时间:2013-03-21 11:05:14

标签: excel-vba vba excel

我想要实现的是根据特定条件将数据从WS1复制到WS3。

我有2个工作表:

WS1 = RAW DATA  
WS2 = ATLAS DATA

在两个列A中都有唯一标识符。我想要做的是创建WS3=Reconciliation。然后在WS2中查找WS1中的值。如果找到匹配,我想将行从WS1复制到WS3 我已经反向设计了一些代码并在下面提出了一个代码

Sub CopyAndPaste()
Dim x As String, CpyRng As Range
Dim mFIND As Range, mFIRST As Range

    With Sheets("RAW DATA")
        Range("A:A").Select
        On Error Resume Next
End With
With Sheets("ATLAS DATA")
        Set mFIND = .Range("A:A").Find(x, LookIn:=xlValues, LookAt:=xlWhole)
        If Not mFIND Is Nothing Then
            Set CpyRng = mFIND
            Set mFIRST = mFIND

            Do
                Set CpyRng = Union(CpyRng, mFIND)
                Set mFIND = .Range("A:A").FindNext(mFIND)
            Loop Until mFIND.Address = mFIRST.Address

            CpyRng.EntireRow.Copy Sheets("Rec").Range("A" & Rows.Count).End(xlUp).Offset(1)
        End If
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

根据您对问题的描述;试试这个

Option Explicit

Sub CopyAndPaste()
Application.ScreenUpdating = False

    Dim i As Long, j As Long, lastRow1 As Long, lastRow2 As Long, cnt As Long
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Set ws1 = ActiveWorkbook.Sheets("RAW DATA")
    Set ws2 = ActiveWorkbook.Sheets("ATLAS DATA")
    Set ws3 = ActiveWorkbook.Sheets("Reconciliation")

    lastRow1 = ws1.Range("A" & Rows.Count).End(xlUp).Row
    lastRow2 = ws2.Range("A" & Rows.Count).End(xlUp).Row
    cnt = 1

    For i = 1 To lastRow1
        For j = 1 To lastRow2
            If StrComp(CStr(ws2.Range("A" & j).Value), _
                       CStr(ws1.Range("A" & i).Value), _
                       vbTextCompare) = 0 Then
                        ws1.Activate
                        ws1.Rows(i).Select
                        Selection.Copy
                        ws3.Activate
                        ws3.Range("A" & cnt).Select
                        Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme
                        Application.CutCopyMode = False
                        cnt = cnt + 1
            End If
        Next j
    Next i
Application.ScreenUpdating = True
End Sub