I need to compare 2 cells in different sheets and get a value if there's a match. I currently have this piece of code, it each cell in column B is checked to each cell in column A and if there's a match the corresponding cell in column C is copied. So far so good, the problem is, it takes a long time to do so. I only have 750 records in column B and 4000 in column A.
Are there ways to optimize the code so it runs faster?
For i = 2 To LastRow
For j = 2 To LastRowJ
If Sheets("tempsheet").Range("B" & i).Value = Sheets("tempsheet").Range("A" & j).Value Then
Range("Q" & i).Value = Sheets("tempsheet").Range("C" & j).Value
End If
Next j
Next i
Here are 6 measurements:
In my test file I had all values on the same sheet (
lr = 4000: lrj = 750
).
Duration copyValsCell1(): 90.78125 sec
Try this:
Find
returns aRange
object of the first found match in the column andNothing
if no match is found. I didn't check the run time but it should be faster than the double for loop.You could use a dictionary keyed to the values in Column A -- assuming that these values are all distinct (otherwise your code itself doesn't quite make sense. Include a reference to Microsoft Scripting Runtime (via
Tools/References
in the VBA editor). The following code should be over 100 times as fast as what you currently have: