I am using realtime data of TOS on 0DTE,I got this macro,what is wrong with the timer,why is it not copying every 15 minutes in my excel files
Code:
Option Explicit
Public NextRun As Date
Public TimerRunning As Boolean
Const MARKET_OPEN As String = "06:30:00"
Const MARKET_CLOSE As String = "13:00:00"
Const SOURCE_COL As String = "F"
Const SOURCE_FIRST_ROW As Long = 13
Const SOURCE_LAST_ROW As Long = 113
Const DEST_START_COL As Long = 6 ' F
Const DEST_FIRST_ROW As Long = 120 ' F120
Const TIME_ROW As Long = 118 ' F118
Const INTERVAL_MINUTES As Long = 15
Sub StartMarketTimer()
Dim nowTime As Date
nowTime = Time
If TimerRunning Then
MsgBox "Timer is already running.", vbInformation
Exit Sub
End If
TimerRunning = True
If nowTime < TimeValue(MARKET_OPEN) Then
NextRun = Date + TimeValue(MARKET_OPEN)
Application.OnTime EarliestTime:=NextRun, Procedure:="RunTimedCopy", Schedule:=True
MsgBox "Timer armed for 6:30 AM Pacific.", vbInformation
ElseIf nowTime >= TimeValue(MARKET_OPEN) And nowTime <= TimeValue(MARKET_CLOSE) Then
RunTimedCopy
Else
TimerRunning = False
MsgBox "Market is already closed for today.", vbExclamation
End If
End Sub
Sub StopTimer()
On Error Resume Next
TimerRunning = False
Application.OnTime EarliestTime:=NextRun, Procedure:="RunTimedCopy", Schedule:=False
On Error GoTo 0
MsgBox "Timer stopped.", vbInformation
End Sub
Sub RunTimedCopy()
Dim nextTime As Date
If Not TimerRunning Then Exit Sub
If Time < TimeValue(MARKET_OPEN) Or Time > TimeValue(MARKET_CLOSE) Then
TimerRunning = False
Exit Sub
End If
CopySnapshotSideways
nextTime = Now + TimeSerial(0, INTERVAL_MINUTES, 0)
If TimeValue(nextTime) <= TimeValue(MARKET_CLOSE) Then
NextRun = nextTime
Application.OnTime EarliestTime:=NextRun, Procedure:="RunTimedCopy", Schedule:=True
Else
TimerRunning = False
MsgBox "1:00 PM reached. Timer stopped.", vbInformation
End If
End Sub
Sub CopySnapshotSideways()
Dim ws As Worksheet
Dim src As Range
Dim dest As Range
Dim lastUsedCol As Long
Dim nextCol As Long
Dim blockRows As Long
Set ws = ActiveSheet
Set src = ws.Range(SOURCE_COL & SOURCE_FIRST_ROW & ":" & SOURCE_COL & SOURCE_LAST_ROW)
blockRows = src.Rows.Count
lastUsedCol = ws.Cells(TIME_ROW, ws.Columns.Count).End(xlToLeft).Column
If ws.Cells(TIME_ROW, DEST_START_COL).Value = "" And ws.Cells(DEST_FIRST_ROW, DEST_START_COL).Value = "" Then
nextCol = DEST_START_COL
Else
nextCol = lastUsedCol + 1
If nextCol < DEST_START_COL Then nextCol = DEST_START_COL
End If
ws.Cells(TIME_ROW, nextCol).Value = Format(Now, "hh:mm AM/PM")
Set dest = ws.Cells(DEST_FIRST_ROW, nextCol).Resize(blockRows, 1)
dest.Value = src.Value
End Sub
Last edited by a moderator: