patternMinor
Excel .find Macro to write data to archive
Viewed 0 times
excelwritemacrofinddataarchive
Problem
I would like to speed up this piece of code. The macro gets a search variable from the worksheet
"RAW_DATA_ARCHIVE" and then it should find it in the worksheet "RAW DATA". When it finds accordance then the value of column A from worksheet "RAW DATA" will be written in the last column of "RAW_DATA_ARCHIVE".For i = 2 To ws1LRow
SearchString = ws1.Range("A" & i).Value
Set aCell = ws2.Columns(5).Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'If match found
If Not aCell Is Nothing Then
ws1.Cells(i, 80).Value = ws2.Cells(aCell.Row, 1).Value
End If
NextSolution
If I understand correctly what you're doing, then VBA is simply not the right tool for this task. Excel has a built-in
That said, you did post some VBA code, albeit just a loop. Here are some thoughts, mostly on naming style:
Using such meaningful names instantly makes it easier to read the code, which makes it easier to maintain/modify without breaking anything.
It also eliminates the need for explanatory comments:
vs.
A number of things explain why your code is slow.
VLOOKUP function specifically for this purpose - try something like this in column 80 of the RAW_DATA_ARCHIVE sheet:=IFERROR(VLOOKUP(A2,'RAW DATA'!E:E,1,FALSE),"")That said, you did post some VBA code, albeit just a loop. Here are some thoughts, mostly on naming style:
ws1andws2would probably be better off assourceSheetandtargetSheet.
ws1LRowwould be more meaningful as simplylastRow
iis usually fine as a loop counter, but here it has a clear meaning:targetRow
aCellis really asearchResult
Using such meaningful names instantly makes it easier to read the code, which makes it easier to maintain/modify without breaking anything.
It also eliminates the need for explanatory comments:
'If match found
If Not aCell Is Nothing Thenvs.
If Not searchResult Is Nothing ThenA number of things explain why your code is slow.
- You're using procedural code instead of built-in worksheet functions
- You're writing to cells in a loop, presumably with
Application.ScreenUpdating = TrueandApplication.Calculation = xlCalculationAutomatic, which means many things happen every time you write a value into a cell.
Code Snippets
=IFERROR(VLOOKUP(A2,'RAW DATA'!E:E,1,FALSE),"")'If match found
If Not aCell Is Nothing ThenIf Not searchResult Is Nothing ThenContext
StackExchange Code Review Q#86516, answer score: 4
Revisions (0)
No revisions yet.