Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert VBA Now() into seconds to determine total program runtime

I'm working on a problem where I need to determine the total time my program takes to execute. First line of code needs to write the current "Start time" and last lines of code need to write the current "End time". Then I'm subtracting "Start time" - "End Time" = Total Time.

I'm confused how I would use the FORMAT() function within VBA on the value of C2 to convert into seconds? Is there an other function that would work better than FORMAT? Basically I'm confused about Excel's Date Serial values and what they represent.

Code is below

EDIT: Thanks for the responses everyone. Both answers below work for what I'm trying to do.

sub ExecutionTime()

Worksheets("Table").Range("A2").Value = Now()

'All my executable code goes here. It's a relatively small program compiling a table so it
runs very quick. 

Worksheets("Table").Range("B2").Value = Now()
Worksheets("Table").Range("C2").Value = Worksheets("Table").Range("A2").Value - Worksheets("Table").Range("B2").Value

end Sub
like image 930
arooney88 Avatar asked Dec 01 '14 15:12

arooney88


1 Answers

Do not use a Date data member or the Now method to analyze run time of your program. Instead, the Timer function is the most appropriate solution as it returns a Single representing seconds. It will require no type conversion and yields a more accurate result than an integer amount of seconds.

Using LimaNightHawk's answer as a template as you should be storing these in local variables instead of writing directly to the worksheet.

Dim startTime as Single
startTime = Timer()

'  Do stuff

Dim endTime as Single
endTime = Timer()

Dim runTime as Single
runTime = endTime - startTime

Results should be written at the end of the routine.

With Worksheets("Table")
    .Range("A2").Value = startTime
    .Range("B2").Value = endTime 
    .Range("C2").Value = runTime
End With

Documentation on the timer function

like image 108
cheezsteak Avatar answered Oct 12 '22 14:10

cheezsteak