試試這個。請注意,如果已找到該行中的值,則需要有一個空列,該列將臨時保存一個標記 - 在我的示例中,我使用了「I」列,如果該列不爲空,則需要對其進行修改。
Private Sub pasteValues()
Dim i, j, lastG, lastD As Long
' find last row
lastG = Sheets("Global").Cells(Rows.Count, "B").End(xlUp).Row
lastD = Sheets("Details").Cells(Rows.Count, "B").End(xlUp).Row
' loop over values in "Global"
For i = 1 To lastG
lookupVal = Sheets("Global").Cells(i, "B") ' value to find
' loop over values in "details"
For j = 1 To lastD
currVal = Sheets("Details").Cells(j, "B")
If lookupVal = currVal Then
Sheets("Global").Cells(i, "O") = Sheets("Details").Cells(j, "H")
Sheets("Global").Cells(i, "P") = Sheets("Details").Cells(j, "E")
Sheets("Global").Cells(i, "Q") = Sheets("Details").Cells(j, "D")
' mark the row
Sheets("Details").Cells(j, "I") = "marked"
End If
Next j
Next i
' loop over rows in "details" and delete rows which have not been marked
For j = 1 To lastD
If Sheets("Details").Cells(j, "I") <> "marked" Then
' delete unmarked rows
Sheets("Details").Cells(j, "A").EntireRow.Delete
If Sheets("Details").Cells(j, "B") <> "" Then
j = j - 1 ' revert iterator so it doesn't skip rows
End If
Else:
' remove the mark
Sheets("Details").Cells(j, "I") = ""
End If
Next j
End Sub
從閱讀它,我會認爲Vlookup應該做你需要的。是什麼讓你覺得不對? –