JeffGrant
Well-known Member
- Joined
- Apr 7, 2021
- Messages
- 558
- Office Version
- 365
- Platform
- Windows
Good morning all, today I would like to share a solution. I needed VB macros to run automatically using variable times that have been read in from a range. All of the information on the net only talks about using Application.OnTime with a set time or a set interval. My solution, reads in the scheduled time from a range and then runs the macro according to that time.
Using two macros as follows and most importantly a cell value to keep track of row numbers (this is the important part), everything works. I hope this can help somebody.
This is an example of the Results.
The label "Start Row " is in Cell A2.
Using two macros as follows and most importantly a cell value to keep track of row numbers (this is the important part), everything works. I hope this can help somebody.
VBA Code:
Sub SetOnTime2()
With Sheet1
'Read in the row value
i = .Range("A2").Value
'set the UNQUE time value to run the macro
ScheduledTime = .Range("F" & i).Value
Application.OnTime ScheduledTime, "MyCode2"
End With
End Sub
Sub MyCode2()
With Sheet1
'Find last value
irow = .Range("F" & Rows.Count).End(xlUp).Row
If .Range("A2").Value <= irow Then
i = .Range("A2").Value
'Output the Results
.Range("H" & i).Value = "Time is: " & Format(ScheduledTime, "hh:mm:ss")
If i = irow Then
MsgBox "Code Stopped"
'Reset Starting Row value
.Range("A2").Value = 3
Exit Sub
Else
'write out the new row value
.Range("A2").Value = i + 1
End If
'call the first macro to read the next time value
Call SetOnTime2
Else
End If
End With
End Sub
This is an example of the Results.
The label "Start Row " is in Cell A2.
Start Row | Scheduled Time | Unique Time | Result | ||||
3 | |||||||
06:57:00 | 06:57:00 | Time is: 06:57:00 | |||||
06:57:01 | 06:57:01 | Time is: 06:57:01 | |||||
06:57:02 | 06:57:02 | Time is: 06:57:02 | |||||
06:57:03 | 06:57:03 | Time is: 06:57:03 | |||||
06:57:04 | 06:57:04 | Time is: 06:57:04 | |||||
06:57:05 | 06:57:05 | Time is: 06:57:05 | |||||
06:57:06 | 06:57:06 | Time is: 06:57:06 | |||||
06:57:06 | 06:57:10 | Time is: 06:57:10 | |||||
06:57:06 | 06:57:11 | Time is: 06:57:11 | |||||
06:57:06 | 06:57:12 | Time is: 06:57:12 | |||||
06:57:10 | 06:57:13 | Time is: 06:57:13 | |||||
06:57:11 | 06:57:18 | Time is: 06:57:18 | |||||
06:57:12 | 06:57:19 | Time is: 06:57:19 | |||||
06:57:13 | 06:57:20 | Time is: 06:57:20 | |||||
06:57:13 | 06:57:21 | Time is: 06:57:21 | |||||
06:57:13 | 06:57:22 | Time is: 06:57:22 | |||||
06:57:13 | 06:57:23 | Time is: 06:57:23 | |||||
06:57:13 | |||||||
06:57:18 | |||||||
06:57:19 | |||||||
06:57:20 | |||||||
06:57:21 | |||||||
06:57:22 | |||||||
06:57:23 | |||||||