Option Explicit
Public RunWhen As Double
Public Const cStartTime = "09:30:00"
Public Const cEndTime = "16:00:00"
Public Const cRunInterval = "00:15:00"
Public Const cRunWhat = "Index_Analysis" 'name of procedure to run
Public Sub StartTimer()
'If current time is earlier than start time, schedule the macro to start today, otherwise the start time has already passed so start
'it tomorrow
If Now < Int(Now) + TimeValue(cStartTime) Then
RunWhen = Int(Now) + TimeValue(cStartTime)
Else
RunWhen = Int(Now) + 1 + TimeValue(cStartTime)
End If
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=True
End Sub
Public Sub RestartTimer()
Dim d As Integer
'If end time is earlier than start time then time range spans midnight so add 1 day to end time to make it occur tomorrow
d = 0
If TimeValue(cEndTime) < TimeValue(cStartTime) Then d = 1
'If current time is earlier than end time, reschedule the macro to run again after the time interval, otherwise stop the timer
If Now < Int(Now) + d + TimeValue(cEndTime) Then
RunWhen = Now + TimeValue(cRunInterval)
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=True
Else
StopTimer
End If
End Sub
Public Sub StopTimer()
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, Schedule:=False
MsgBox cRunWhat & " stopped"
End Sub
Sub Index_Analysis()
'Call StartTimer to schedule the procedure again
RestartTimer
'Put your code here
'==================
End Sub