niko
niko

Reputation: 9393

which is faster ,a variable or direct access of the cell value?

well I have lots of string manipulations like

1st one
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, ",", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "/", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "&", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "(", " ")
2nd one
store=ActiveSheet.Cells(i, "B").Value
store= Replace(store, "/", " ")
store = Replace(store, "&", " ")
store = Replace(store, "(", " ")

and some trim operations and sometimes finding string length and sometimes comparison.

I have to do looping for cells 1 to 4000. The question is storing the cell value in string and accessing is better and faster? or writing the activesheet cell value in the macro is itself faster?

store = activesheet.cells(i,"B").value and use store everywhere 
or write activesheet.cells(i,"B").value everywhere?

Which is better which is more optimized I was kinda thinking if we mention the cell value it has to go to sheet and get it back but if we store it in variable then it might be faster. I just need to know which is better ?

Upvotes: 1

Views: 1989

Answers (1)

Gaijinhunter
Gaijinhunter

Reputation: 14685

Accessing Excel is slow. Storing things you'll access more than twice in a variable will always be faster, and dumping a range of cells (one call to Excel) into a variant array is even better.

Remember, Excel and VBA are not the same. It's like two guys in the same flat but different rooms. Everytime you access Excel, VBA has to knock on Excel's door.

Update: The above is general advice for all code. Concerning the particular code above and what you are doing, it might actually be faster to use Excel's search and replace functionality on the range like so:

Sub test()

Application.ScreenUpdating = False
With Range("B1:B4000")
    .Replace what:="(", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    .Replace what:="&", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    .Replace what:="/", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End With
Application.ScreenUpdating = True
End Sub

Upvotes: 7

Related Questions