New to VBA - How to Make my Code more Efficient

craigjones1203

New Member
Joined
Apr 9, 2021
Messages
2
Office Version
  1. 2013
Platform
  1. Windows
Hey everyone - new VBA user here!

I'm working on trying to make a repetitive task easier with VBA and have been having issues with my code taking a really long time to run or the file just crashing. For reference, I'll typically be dealing with ~50,000 rows of data. What I'm trying to do is use a VLookup function for a table on a different sheet but it keeps crashing for larger sets of data. Does anyone have any tips for how to make more efficient? Any tips are appreciated!

Code below:

Dim last As Long
Dim i as Long
last = Cells.Find(What:="*", SearchDirection:=xlPrevious).Row
i = 1

For Each Cell In Range ("Q2:Q" & last)
i = i + 1

Cell.Value = Application.VLookup(Range("F" & i), Worksheets("Revenue").Range("A:E"), 5, False)
Range("R" & i) = Application.VLookup(Range("F" & i), Worksheets("Revenue").Range("A:E"), 4, False)

Next
 

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
The biggest tip would be to work with arrays in vba and not write to cells repeatedly, use one bulk write.

VBA Code:
Dim outputArray as Variant
Dim last As Long
Dim i as Long
last = Cells.Find(What:="*", SearchDirection:=xlPrevious).Row

ReDim outputArray(2 to last, 1 to 2)

For i = 2 to last
    outputarray(i, 1) = Application.VLookup(Range("F" & i), Worksheets("Revenue").Range("A:E"), 5, False)
    outputArray(i, 2) = Application.VLookup(Range("F" & i), Worksheets("Revenue").Range("A:E"), 4, False)
Next i

Range("Q2").Resize(Ubound(outputarray,1), Ubound(outputArray, 2)).Value = outputArray
 
Upvote 0

Forum statistics

Threads
1,213,562
Messages
6,114,326
Members
448,564
Latest member
ED38

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top