I have 18000 items with a CPV product code in one workbook, and each of these CPV codes correspond to a UNSPC code which can be found in one of 45 workbooks in a particular folder. For each CPV code I want to search through each of these other workbooks until it is found, and then copy the corresponding UNSPC code to the cell in the column directly next to the CPV code in the original workbook.
Currently, my code is:
Sub findUNSPC()
Dim file As String
Dim app As New Excel.Application
Dim book As Excel.Workbook
Dim StartNumber As Integer, EndNumber As Integer, check As Integer, cpv As Long, unspc As Long
EndNumber = Sheet2.Range("D" & Rows.Count).End(xlUp).Row
For StartNumber = 2 To EndNumber
Sheet2.Cells(StartNumber, 4).Activate
cpv = ActiveCell.Value
file = Dir("C:\Users\Gylfi.heimisson\Documents\Enzen\CPV to UNSPSC\" & "*.xlsx")
Do While Len(file) > 0
Debug.Print file
file = Dir
Set book = app.Workbooks.Add("Source Directory" & file) 'Source Directory is just where the files are located on my computer
book.Worksheets("Mappings").Activate
check = book.Application.WorksheetFunction.Match(cpv, "B:B", 0)
If check <> "#N/A" Then
unspc = book.Application.WorksheetFunction.Index("S:S", check)
End If
Loop
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
ActiveCell.Offset(0, 1).Value = usnpc
Next StartNumber
End Sub
I am getting a Runtime Error '1004': Application-defined or object-defined error" at line 17. I am also unsure about the rest of the code.
I realise that I have probably written this in an inefficient way as well, so any suggestions on what I've done wrong, and how to make it work, will be greatly appreciated!