dimanche 1 mars 2015

excel vba macro to match cells from two different workbooks and copy and paste accordingly

i have 2 workbooks, workbook A and workbook B. Each workbook has a table. workbook A has 2 columns. All three columns are filled.



  1. product_id

  2. Machine_number and


Workbook B has the same 2 columns but only one column, Product_id, is filled. The other 1 column is vacant.


I need to match the cells of product_id of both workbooks. If the product_id found in workbook A matches workbook B, then the machine number of that product id should be copied from workbook A to workbook B.


I have performed this using this code:



Sub UpdateW2()

Dim w1 As Worksheet, w2 As Worksheet
Dim c As Range, FR As Long

Application.ScreenUpdating = False

Set w1 = Workbooks("workbookA.xlsm").Worksheets("Sheet1")
Set w2 = Workbooks("workbookB.xlsm").Worksheets("Sheet1")


For Each c In w1.Range("A2", w1.Range("A" & Rows.Count).End(xlUp))
FR = 0
On Error Resume Next
FR = Application.Match(c, w2.Columns("A"), 0)
On Error GoTo 0
If FR <> 0 Then w2.Range("C" & FR).Value = c.Offset(, 0)
Next c
Application.ScreenUpdating = True
End Sub


There is a cell that says "machine 4" in product number column. This cell does not get copied and pasted alongside the corresponding product_id value in workbook B.


The rest of the machine numbers for the product ids get copied and pasted accordingly.


These are the screenshots of results enter image description here enter image description here


The first screenshot is Workbook B


The second screenshot is Workbook A


I have no idea why this happens, can someone please give me the reason for this?


................................................................................ UPDATE


I found that the issue ive descriped in the question arises when the product_id(style_number) repeats.


Say if product_id GE 55950 is present in 2 cells,in both workbooks. Then when i execute the macro only one of the cells is detected.


I tried the coding in both answers but neither solved this problem.


Below is a screenshot of the results. enter image description here enter image description here


In the screenshots the cell with machine 7 is not shown


Aucun commentaire:

Enregistrer un commentaire