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 Workbook
Dim wsSrc As Worksheet
Dim wbDest As Workbook
Dim wsDest As Worksheet
Dim cmpstr As String
Dim valuestr As String
Dim rowIndex As Integer
Dim totalRows As Integer
Dim result_Index As Long
Dim file_name As String
Dim LastRow As Long
file_name = get_File_Name("Old")
If file_name <> "" Then
Set 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 <> "" Then
Set wbDest = Workbooks.Open(Filename:=file_name)
Set wsDest = wbDest.Worksheets(1)
' Total rows in Column A in destination workbook
totalRows = wsDest.Range("A1").End(xlDown).Row
' Total rows in Column A in source workbook
LastRow = wsSrc.Range("A1").End(xlDown).Row
' Loop in destination rows
For rowIndex = 1 To totalRows
cmpstr = wsDest.Cells(rowIndex, 1).Value
' loop in source rows
For result_Index = 1 To LastRow
If Not IsError(Application.Match(cmpstr, wsSrc.Cells(result_Index, 1), 0)) Then
wsDest.Cells(rowIndex, 2).Value = wsSrc.Cells(result_Index, 2)
End If
Next result_Index
Next rowIndex
wbDest.Save
MsgBox "Users were Successfully copied."
Else
MsgBox "An error has Occured"
End If
Else
MsgBox "An error has Occured"
End If
End 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 String
title = "Please choose the " & str & " Report Excel file"
FileToOpen = Application.GetOpenFilename _
(title:=title, _
FileFilter:="Excel Files *.xlsx (*.xlsx),")
''
If FileToOpen = False Then
MsgBox "No file specified.", vbExclamation, "Error!"
get_File_Name = ""
Else
get_File_Name = FileToOpen
End If
End 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: