Put this code inside a new Class module & call the module something like Stopwatch:
' **********************************************
' Start Code
' **********************************************
Option Explicit
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private mlngStart As Long
Public Sub StartTimer()
' Store away the starting time.
mlngStart = timeGetTime
End Sub
Property Get IsRunning() As Boolean
' Return True if the stopwatch is running, False otherwise.
IsRunning = (mlngStart <> 0)
End Property
Property Get ElapsedTime() As Long
' Return the elapsed time.
If IsRunning Then
ElapsedTime = (timeGetTime - mlngStart)
Else
ElapsedTime = 0
End If
End Property
Property Get TimerStarted() As Long
' Return the starting time.
TimerStarted = mlngStart
End Property
Public Function StopTimer() As Long
' Retrieve the elapsed time, and reset the start time to 0 (so IsRunning will think you're not currently running).
If IsRunning Then
StopTimer = (timeGetTime - mlngStart)
Else
StopTimer = 0
End If
' Reset the timer.
mlngStart = 0
End Function
' **********************************************
' End Code
' **********************************************
Now in any other sub / function in any other module (in the same project) you can use our new Stopwatch with the following code:
' **********************************************
' Start Code
' **********************************************
Dim my Timer as Stopwatch ' NB must be same as Class module name
' ... Other code
Set myTimer = New Stopwatch ' Intialise object
' ... Other Code
myTimer.StartTimer
' ... Main Body of Function / Sub
MsgBox "Function / Sub took " & myTimer.ElapsedTime & _
" milliseconds to run"
' ... Other Code
' **********************************************
' End Code
' **********************************************
HTH,
James
|