Hello, I have a VBA code that compares values in key column on worksheet 1 with one by one value in key column in worksheet 2 (column header selected by user). When (and if) the key values on worksheet 2 match with value in key column on worksheet 1 than it copies several columns from worksheet 2 to worksheet 1 (column headers in range that has to be copied is also selected by user).
It is like VLOOKUP but more cells are copied.
Both worksheets have the same number and distribution of columns but different number of rows.
I have some 3000 rows in both sheets and it takes couple of minutes for code to finish. I suppose matching and copying could be optimized. This is the vital part of the code:
How could I optimize this part of the code?
Here is the complete code:
It is like VLOOKUP but more cells are copied.
Both worksheets have the same number and distribution of columns but different number of rows.
I have some 3000 rows in both sheets and it takes couple of minutes for code to finish. I suppose matching and copying could be optimized. This is the vital part of the code:
VBA Code:
For i = 1 To nrs1 - 1
j = 1
Do While j < nrs2
If Worksheets(1).Range(addr1).Offset(i, 0).Value = Worksheets(2).Range(addr1).Offset(j, 0).Value Then
Worksheets(1).Range(addr2).Offset(i, 0).Value = Worksheets(2).Range(addr2).Offset(j, 0).Value
Exit Do
End If
j = j + 1
Loop
Next i
How could I optimize this part of the code?
Here is the complete code:
VBA Code:
Sub MatchAndCopy()
Dim nrs1 As Integer, nrs2 As Integer, i As Integer, j As Integer
Dim rng1 As Range, rng2 As Range, addr1 As String, addr2 As String
Set rng1 = Application.InputBox("Select column for match", , , , , , , 8)
addr1 = rng1.Address
Set rng2 = Application.InputBox("Select columns for copy", , , , , , , 8)
addr2 = rng2.Address
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Worksheets(1).Select
Range("A1").Select
nrs1 = Selection.CurrentRegion.Rows.Count
Worksheets(2).Select
Range("A1").Select
nrs2 = Selection.CurrentRegion.Rows.Count
For i = 1 To nrs1 - 1
j = 1
Do While j < nrs2
If Worksheets(1).Range(addr1).Offset(i, 0).Value = Worksheets(2).Range(addr1).Offset(j, 0).Value Then
Worksheets(1).Range(addr2).Offset(i, 0).Value = Worksheets(2).Range(addr2).Offset(j, 0).Value
Exit Do
End If
j = j + 1
Loop
Next i
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub