簡體   English   中英

比較兩個工作表,找到第一個匹配項並粘貼,然后刪除源行

[英]Compare two worksheets, find first match and paste, then delete source row

我有兩個工作表,並且想在活動工作表中找到第一個匹配項時從第二個工作表(Sheet1)中粘貼兩個單元格。 然后刪除Sheet1中的源行。 我無法從活動工作表的最后一行開始循環,因為我想從匹配的頂部開始填充第一行。 我也正在努力激活Sheet1以刪除該行:

Sub moveRecords()
Dim i, j As Long
With ActiveSheet
    'need to work down in active sheet in order to populate the first match with cells 1 & 2
    For i = 2 To 100
        For j = 2 To 1000
           If Cells(n, 1).Value = Sheets("Sheet1").Cells(j, 1).Value _
           And Cells(n, 2).Value = Sheets("Sheet1").Cells(j, 2).Value Then
               Cells(n, 7).Value = Sheets("Sheet1").Cells(j, 1).Value
               Cells(n, 8).Value = Sheets("Sheet1").Cells(j, 2).Value
           'need to delete the source row in Sheet1
           End If
        Next j
    Next n
End With
End Sub

這是一種略有不同的方法,因為您要刪除整行,因此很難正確跟蹤i或j變量,因此此代碼將所有復制和粘貼標記為必須刪除的行,然后將其全部刪除,我對您的要求感到困惑,但我認為就是這樣=]

Sub moveRecords()

        For j = 2 To 100
           If Sheets("Sheet1").Cells(j, 1).Value = Sheets("Sheet2").Cells(j, 1).Value _
           And Sheets("Sheet1").Cells(j, 2).Value = Sheets("Sheet2").Cells(j, 2).Value Then
               Sheets("Sheet1").Cells(j, 7).Value = Sheets("Sheet2").Cells(j, 1).Value
               Sheets("Sheet1").Cells(j, 8).Value = Sheets("Sheet2").Cells(j, 2).Value
               Worksheets("Sheet2").Cells(j, 1) = "Delete"
           End If
        Next

        For i = 2 To 100
           If Worksheets("Sheet2").Cells(i, 1) = "Delete" Then
           Worksheets("Sheet2").Cells(i, 1).EntireRow.Delete
           i = i - 1
           End If
        Next

End Sub

如果您在sheet1和sheet2上的數據如下所示:

在此處輸入圖片說明在此處輸入圖片說明

解決方法如下:

Sub test()

Set ExcelApp = CreateObject("Excel.Application")
Set wb = ActiveWorkbook
Set ws = wb.Worksheets("Sheet1")
Set ws1 = wb.Worksheets("Sheet2")
Set Rng = ws.UsedRange
RowCount = Rng.Rows.Count
Set Rng1 = ws1.UsedRange
RowCount1 = Rng.Rows.Count
For n = 1 To RowCount
    For j = 1 To RowCount1
       If ws.Cells(n, 1).Value = ws1.Cells(j, 1).Value _
       And ws.Cells(n, 2).Value = ws1.Cells(j, 2).Value Then
           ws.Cells(n, 7).Value = ws1.Cells(j, 1).Value
           ws.Cells(n, 8).Value = ws1.Cells(j, 2).Value
           ws1.Cells(j, 1).EntireRow.Delete
        'To set the search to start from top row
        j = 0
       End If
    Next j
Next n


End Sub

輸出將是:

在此處輸入圖片說明在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM