![](/img/trans.png)
[英]How to copy "specific" rows from one sheet and paste in to another in an excel using VBA Macros
[英]Excel Vba - How to copy and paste matched rows from one sheet to below exact matched rows in another sheet
我在excel vba場景中還很新。 我要在此宏中完成的任務是,
我有兩張紙,兩列,sheet1列A,sheet2列A,在A列中都有可能的匹配項。我試圖找到兩張紙之間的所有匹配項,並將匹配的整個行從sheet1復制到恰好在第二張中的匹配行以下與sheet1的標題。
工作表Sheet1
數據-----------名
012 ----------- AAA
022 ----------- BBB
033 ----------- CCC
Sheet2中
ID -----------地址
012 ----------- NYC
021 -----------費城
033 ----------- CT
結果
ID -----------地址
012 ----------- NYC
數據-----------名
012 ----------- AAA
021 -----------費城
033 ----------- CT
數據-----------名
033 ----------- CCC
到目前為止,我所擁有的代碼僅復制第一行,不知道如何解決。
Sub oneMacro()
Dim lastrowone As Integer, lastrowtwo As Integer
lastrowone = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
lastrowtwo = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrowone
For j = 2 To lastrowtwo
If Sheets("Sheet1").Cells(i, "A").Value = Sheets("Sheet2").Cells(j, "A").Value Then
Sheets("Sheet1").Cells(i, "A").EntireRow.Copy
Sheets("Sheet2").Cells(j, "A").Offset(1).Insert Shift:=xlDown
End If
Next j
Next i
End Sub
您的代碼有兩個問題。 首先,為了幫助您了解如何解決此問題...首先,您需要添加一些斷點,並設置一些手表。 但是您會看到循環一開始就已完全設置,但是在添加數據時無法正確適應。
幾乎您的loop語句繼續循環,直到您命中的lastrowtwo
最初設置為3(基於上面的示例)。 相反,每次您向lastrowtwo
變量找到真實結果時,您的代碼就需要加+1
。 我已經在下面修改了您的代碼以解決此問題。
另一個問題是您正在處理從一個單元到另一個單元的所有內容,然后將其向下移動。 這樣做時,您將比較下一個(作為匹配項返回)。 片刻之后,您會看到這只會掃描第一個訂單項。 為了克服這個問題,您可以簡單地跳過循環檢查語句中的下一行。 您可以通過將j
變量加+1
來實現。 參見下面的修改。
Sub oneMacro()
Dim lastrowone, lastrowtwo As Long
lastrowone = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
lastrowtwo = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrowone
For j = 2 To lastrowtwo
If Sheets("Sheet1").Cells(i, 1).Value = Sheets("Sheet2").Cells(j, 1).Value Then
Sheets("Sheet1").Cells(i, 1).EntireRow.Copy
Sheets("Sheet2").Cells(j, 1).Offset(1).Insert Shift:=xlDown
j = j + 1 ' Modified = this must be added to overcome an issue with DOUBLE checking the newly inserted data
lastrowtwo = lastrowtwo + 1 ' Modified = This is added to overcome an issue with not completing all rows
End If
Next j
Next i
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.