I have two excels Book1.xlsm and Book2.xlsx. Book1 will have certain values like alpha, beta, gamma etc. (no repetition) in column A. And Book2 will have multiple occurrence of Book1 values like beta, beta, beta, alpha, alpha, gamma, gamma, gamma, gamma, gamma etc. The values in Book2 may not be alphabetically sorted but same values will be grouped together. Book2 values will be also in column A.
I have a macro designed in Book1.xlsm that should iterate over each value in Book1 column A and find the first row id where same value is present in Book2 column A. This row id should be then copied in corresponding column B of Book1. This is how my macro code looks like. When I run, it fails with Run Time error '1004': Application-defined or object-defined error
Option Explicit
Sub Get_Data()
Dim wb1 As Worksheet
Dim wb2 As Worksheet
Dim wb2row As Integer
Dim i As Integer
Dim j As Integer
Const A = "A"
Const B = "B"
Set wb1 = Workbooks("Book1.xlsm").Worksheets("Sheet1")
Set wb2 = Workbooks("Book2.xlsx").Worksheets("Sheet1")
'Both For loop start from row id 2.
For i = 2 To wb1.Range("A2", wb1.Range("A2").End(xlDown)).Rows.Count
For j = 2 To wb2.Range("A2", wb2.Range("A2").End(xlDown)).Rows.Count
wb2row = Application.WorksheetFunction.Match(wb1.Cells(i, A), Range(wb2.Cells(j, A)), 0)
wb1.Cells(i, B).Copy (wb2.Cells(j, A))
Exit For ' j loop
Next j
Next i
End Sub
Range(wb2.Cells(j, A))
in theMatch
function is probably the cause of the error. Try replacing it withwb2.Range("A:A")
. (2) Why theFor j
loop if you're using theMatch
function? (3)wb1.Cells(i, B).Copy (wb2.Cells(j, A))
doesn't go with the logic you outlined. Shouldn't you havewb1.Cells(i, B) = wb2row
instead? – Super SymmetryUnable to get the Match property of the WorksheetFunction class
, it means that the function could not get a match and you have to do some error handling as @VBasic2008 's answer suggests. Both errors have the same number (1004) – Super Symmetrywb1.Cells(i, B).Copy (wb2.Cells(j, A))
you surround the the destination of theCopy
method with parentheses. This passes the value of the range to theCopy
method rather than the range itself. Therefore, that line has the same effect aswb1.Cells(i, B).Copy wb2.Cells(j, A).Value
and this will cause another run-time error – Super Symmetry