Copy the following code into an empty VBA module:


Option Explicit

Private Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Private Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long

Private iTimer As Integer                              'the timer identifier
Private Const lDelay As Long = 5000                    'the time in ms between WM_TIMER events

Private Function TimerProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal iTimerID As Long, ByVal dwTime As Long) As Long
 
   KillTimer 0&, iTimer                                              'stop timer
   Debug.Print Time
   
End Function

Sub CATMain()
   
   Debug.Print Time
   iTimer = SetTimer(0&, 0&, lDelay, AddressOf TimerProc)           'start the timer

End Sub


This macro prints the time in the 'Immediate Window' of the VBA-IDE per Debug.Print and then starts a timer.

After 5 sec. another Debug.Print in Timer-Proc prints the time again.

Any other piece of code could be executed instead of a call to Debug.Print.

If the Timer is restarted again within TimerProc, it has to be stopped elsewhere in the code prior to the end of the macro.

Go to top