Option Explicit
Code that handles the copying
Takes every value in Column A of the Destination and checks if it exists column A of the Source file if a match occurs takes the value of column B of the same row and copies it in the column B of the Destination file in the same row of the original compared value
Sub Button2_Click()Dim wbSrc As WorkbookDim wsSrc As WorksheetDim wbDest As WorkbookDim wsDest As WorksheetDim cmpstr As StringDim valuestr As StringDim rowIndex As IntegerDim totalRows As IntegerDim result_Index As LongDim file_name As StringDim LastRow As Longfile_name = get_File_Name("Old")If file_name <> "" ThenSet wbSrc = Workbooks.Open(Filename:=file_name)Set wsSrc = wbSrc.Worksheets(1)file_name = get_File_Name("Dest")'MsgBox file_name, vbExclamation, "Debug!!!"If file_name <> "" ThenSet wbDest = Workbooks.Open(Filename:=file_name)Set wsDest = wbDest.Worksheets(1)' Total rows in Column A in destination workbooktotalRows = wsDest.Range("A1").End(xlDown).Row' Total rows in Column A in source workbookLastRow = wsSrc.Range("A1").End(xlDown).Row' Loop in destination rowsFor rowIndex = 1 To totalRowscmpstr = wsDest.Cells(rowIndex, 1).Value' loop in source rowsFor result_Index = 1 To LastRowIf Not IsError(Application.Match(cmpstr, wsSrc.Cells(result_Index, 1), 0)) ThenwsDest.Cells(rowIndex, 2).Value = wsSrc.Cells(result_Index, 2)End IfNext result_IndexNext rowIndexwbDest.SaveMsgBox "Users were Successfully copied."ElseMsgBox "An error has Occured"End IfElseMsgBox "An error has Occured"End IfEnd Sub
Open dialog function and returns the path to the file or an empty string
Public Function get_File_Name(str As String)Dim title As Stringtitle = "Please choose the " & str & " Report Excel file"FileToOpen = Application.GetOpenFilename _(title:=title, _FileFilter:="Excel Files *.xlsx (*.xlsx),")''If FileToOpen = False ThenMsgBox "No file specified.", vbExclamation, "Error!"get_File_Name = ""Elseget_File_Name = FileToOpenEnd IfEnd Function
I by no way claim this is the best way to do it. If you have better code for this job please share and post code or link of your work in the comment. In that case I would update the code and give you credit for your work.
Please like & share: