根据id更新对行

时间:2016-06-21 21:21:13

标签: excel vba excel-vba

我使用此代码将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

我想编写一个算法来检查,如果在copySheet的A列的任何单元格中有与pasteSheets值相同的值,那么pasteSheet中B列的单元格将具有copysheet的B列值。

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

有了这个,我将根据ID(A列)更新产品数量(B列)。我希望我的问题很明确,希望得到建议。

1 个答案:

答案 0 :(得分:1)

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