Option Explicit
Private Declare Function GetForegroundWindow Lib "user32" () As Long
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 Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private lngTimerID As Long
Private strTrackSheet As String
Private lngXlMainHwnd As Long
Private dblTotalTime As Double
Public Sub StartTimer(strSheetName As String)
strTrackSheet = strSheetName
lngXlMainHwnd = FindWindow("XLMAIN", vbNullString)
dblTotalTime = 0
lngTimerID = SetTimer(0, 1, 1000, AddressOf RunTimer)
End Sub
Public Sub StopTimer()
Dim lRet As Long
lRet = KillTimer(0, lngTimerID)
End Sub
Private Sub RunTimer(ByVal hwnd As Long, _
ByVal uint1 As Long, _
ByVal nEventId As Long, _
ByVal dwParam As Long)
On Error Resume Next
Dim lngFrontWin As Long
lngFrontWin = GetForegroundWindow()
If ActiveSheet.Name = strTrackSheet _
And lngXlMainHwnd = lngFrontWin Then
dblTotalTime = dblTotalTime + 0.0000115741
Range("A1").Value = dblTotalTime
End If
End Sub
Public Sub Example()
Call StartTimer("Sheet1")
End Sub