I am trying to use multiple Application.OnTime inside my sub and I am getting the unexpected results.
This is what I want to do:
Run a sub (testOnTime) every 1 minute using a "recursive" call
Inside sub (testOnTime):
run "firstSection" 10 seconds after entering the sub (testOnTime)
Inside "firstSection": write debug msgs to Excel sheet "MySheet"
run "lastSection" 40 seconds after entering the sub (testOnTime)
Inside "lastSection": write debug msgs to Excel sheet "MySheet"
Write debug msgs to Excel sheet "Mysheet"
has sub "testOnTime" run 5 times?: No -> continue , yes -> exit
Code:
Option Explicit
Public rowCnt As Integer
Public Cnt As Integer
Public Const sheetName = "MySheet"
Public Const inc1 = "00:00:40"
Public Const inc2 = "00:00:10"
Public timeStr1 As Date
Public timeStr2 As Date
Public timeStr3 As Date
Public Sub MyMain()
rowCnt = 1
Cnt = 0
Call testOnTime
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "Done"
End Sub
Public Sub testOnTime()
' wait-time for last section
timeStr1 = Format(Now + TimeValue(inc1), "hh:mm:ss")
' wait time for first section
timeStr2 = Format(Now + TimeValue(inc2), "hh:mm:ss")
' wait for 1 minute
timeStr3 = Format(Now + TimeValue("00:01:00"), "hh:mm:ss")
' wait utill 10 seconds
Application.OnTime TimeValue(timeStr2), "firstSection"
' wait utill 40 seconds
Application.OnTime TimeValue(timeStr1), "lastSection"
' debug msgs
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "Outside @ " & CStr(timeStr3)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
Cnt = Cnt + 1
If Cnt < 5 Then
' wait until Now + 1 min
Application.OnTime TimeValue(timeStr3), "testOnTime"
End If
End Sub
Public Sub firstSection()
' debug msgs for first section
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "In first section @ " & CStr(timeStr2)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
End Sub
Public Sub lastSection()
' debug msgs for first section
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "In last section @ " & CStr(timeStr1)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
End Sub

Why does "Outside..." get written first to the excel sheet, when it is supposed to be last instruction inside the macro?
Why does the macro output "two" msgs of the same thing when it should be outputting only once?
Is there a better way of acheiving my desired goal without use of "OnTime"?
rowcnt=cells(rows.count,1).end(xlup).row- Patrick Lepelletier