Home » excel » excel – Matching data from two workbooks based on ID column and updating data in two columns of first workbook where IDs match

excel – Matching data from two workbooks based on ID column and updating data in two columns of first workbook where IDs match

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m attempting to do something like this:

Workbook 1

   B  R   S
   1  22  41
   2  43  22
   4  55  30
   5  72  0

Workbook 2

    B  R  S
    5  13 43 
    3  34 23
    1  20 4
    2  89 90

Workbook 1 (updated after Macro matches IDs in Column B and pastes data from workbook 2 to Columns R & S)

   B   R  S
   1   20 4
   2   89 90 
   4   55 30
   5   13 43

Essentially I’m trying to match the IDs in column A of the workbooks and have any data in column B and c of workbook 2, in the rows that have the matching IDs, to be pasted over the cells of B and C in workbook 1.

This is the code I’ve managed to cobble together based on this question appending data based on condition (Thanks to the person who asked the question and the person who answered it!)

   Sub Update_Worksheet()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws1LR As Long, ws2LR As Long
Dim i As Long, j As Long, LastCol As Long
Dim ws1Rng As Range, aCell As Range
Dim SearchString

Set ws1 = Sheets("Sheet1")
'~~> Assuming that ID is in Col B
'~~> Get last row in Col B in Sheet1
ws1LR = ws1.Range("B" & Rows.Count).End(xlUp).Row
'~~> Set the Search Range
Set ws1Rng = ws1.Range("B1:B" & ws1LR)

Set ws2 = Sheets("Sheet2")
'~~> Get last row in Col B in Sheet2
ws2LR = ws2.Range("B" & Rows.Count).End(xlUp).Row

'~~> Loop through the range in Sheet 2 to match it with the range in Sheet1
For i = 1 To ws2LR
    SearchString = ws2.Range("B" & i).Value

    '~~> Search for the ID
    Set aCell = ws1Rng.Find(What:=SearchString, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    '~~> If found
    If Not aCell Is Nothing Then
        LastCol = ws2.Cells(i, ws2.Columns.Count).End(xlToLeft).Column

This is the part I feel I have to change, but not sure how to make it overwrite the columns I need to overwrite with the data: (specifically I need columns R & S of sheet 2 to overwrite R&S of Sheet 1 if the IDs in column A match)

        '~~> Append values
        For j = 2 To LastCol
            ws1.Cells(aCell.Row, j).Value = ws2.Cells(i, j).Value
        Next j
    End If
Next i
End Sub

Any help would be much appreciated!

How to&Answers:

Your question is ambiguous but form my little understanding i modify this for you.

'~~> If found
If Not aCell Is Nothing Then
    '~~> Append values
        ws1.Cells(aCell.Row, 2).Value = ws2.Cells(i, 2).Value
        ws1.Cells(aCell.Row, 18).Value = ws2.Cells(i, 18).Value
        ws1.Cells(aCell.Row, 19).Value = ws2.Cells(i, 19).Value
End If