根据id更新配对行

我复制并粘贴从我的copySheet(列A和B)2列到pasteSheet(列A和B)第一个空行与此代码;

Set copySheet = Worksheets("copySheet") Set pasteSheet = Worksheets("pasteSheet") lRow = copySheet.Cells(copySheet.Rows.Count, 1).End(xlUp).Row With copySheet.Range("A1:A" & lRow) pasteSheet.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(.Rows.Count, .Columns.Count) = .Value End With lRow = copySheet.Cells(copySheet.Rows.Count, 1).End(xlUp).Row With copySheet.Range("B1:B" & lRow) pasteSheet.Cells(Rows.Count, "B").End(xlUp).Offset(1,0).Resize(.Rows.Count, .Columns.Count) = .Value End Sub 

我想编码algorithm来检查,如果copySheet的A列的任何单元格与pasteSheets值具有相同的值,则pasteSheet中B列的单元格将具有copysheet的B列值。

总结一下:我必须在每张表中列出; 列A有ID号,列B有名字。 在复制/粘贴操作期间,如果copysheet的列A具有与pasteSheet的列A中相同的id号,则该对id(copySheet的列B)将被覆盖到列B中的pasteSheet的相应单元格。

有了这个,我会根据ID(列A)更新产品的数量(B列)。 我希望我的问题很清楚,希望能得到build议。

 Sub AddOrUpdate() Dim copySheet As Worksheet, pasteSheet As Worksheet Dim lRow As Long, rw As Long, m, v Set copySheet = Worksheets("copySheet") Set pasteSheet = Worksheets("pasteSheet") lRow = copySheet.Cells(copySheet.Rows.Count, 1).End(xlUp).Row For rw = 1 To lRow v = copySheet.Cells(rw, 1).Value 'id value 'is there an id match on pastesheet Col A? m = Application.Match(v, pasteSheet.Columns(1), 0) If IsError(m) Then 'not matched, so add as new row With pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) .Value = v .Offset(0, 1).Value = copySheet.Cells(rw, 2).Value End With Else 'matched, so just update the amount pasteSheet.Cells(m, 2).Value = copySheet.Cells(rw, 2).Value End If Next rw End Sub