VBA Efficiency - Calculating on the "background" and passing to range -
it's been month since i've started studying , practicing vba in excel , first time ask question in forum, keep in mind.
the problem this:
- i have sheet 300k rows , 10 columns
- each row result of calculation made in script
- the whole script takes 2min31s run
- i'm using ranges , options speed (e.g. "application.calculation = xlmanual", etc)
is safe think performing calculations on memory variable faster using range? i've simplified code use example:
option 1 - how i'm doing right now
for = 0 300000 sheet.cells(i,1).value = i^2 next
option 2 - in head run faster
for = 0 300000 variable(i) = i^2 next 'this doesn't work it's illustrate i'm looking sheet.range(cells(1,1),cells(300000,1)).value = variable
can done? can pass values of array range @ once, avoiding looping through each cell of range?
yes faster, however, need 2 dimensional array of variants.
dim variable(1 1, 1 300000) ' long row (but long row) dim variable(1 300000, 1 1) ' long column
this way save time because pass data through interface once , not 300000 times. , calling method set value property has fix cost because sub in vba editor in same process different apartment excel, cross boundary rpc (remote procedure call) used.
btw, if want know if performance improvement works, should measure it, this:
debug.print "started: " & now() ' code debug.print "finished: " & now()
update
i tried, , work 1 dimensional arrays. in case interpreted long row. however, think it's better use 2 dimensional array version because (1) cleaner (easy see data like) , because (2) data in same format if read range.
update two
so run these:
public sub slowmethod(optional citerations long = 300001) debug.print "started: " & now() dim long: = 0 citerations - 1 activesheet.cells(1 + i, 1).value = ^ 2 next debug.print "finished: " & now() end sub public sub fastmethod(optional citerations long = 300001) debug.print "started: " & now() dim variable() variant: redim variable(1 citerations, 1 1) dim long: = 0 citerations - 1 variable(1 + i, 1) = ^ 2 next activesheet.cells(1, 1).resize(citerations, 1).value = variable debug.print "finished: " & now() end sub
and received:
slowmethod started: 2017.04.06. 15:57:54 finished: 2017.04.06. 15:58:56 fastmethod started: 2017.04.06. 15:59:02 finished: 2017.04.06. 15:59:02
so less 1 second vs more 1 minute.
Comments
Post a Comment