'Excel VBA - Set timer goes faster after each loop
I am trying to create a timer that when reaching zero, it calls from the "Database" script, and then repeats the timer again from 30 seconds. Problem is, every time the timer restarts each tick removes more and more and it won't take long until the script starts repeating every 1 second even though the timer starts at 30.
I have been staring at this for ages now, and I can't figure out what is going on. It clearly states 'cell value = cell value - 1 second'.
What am I missing?
Dim IsOffline As String
Sub Repeater()
IsOffline = ThisWorkbook.Worksheets(3).Range("BC2")
If IsOffline = "Online" Then
RunTimer = Now + TimeValue("00:00:01")
Application.OnTime RunTimer, "NextTick"
End If
End Sub
Sub NextTick()
If ThisWorkbook.Worksheets(3).Range("BC5").Value <= TimeValue("00:00:00") And IsOffline = "Online" Then
Call Database
ThisWorkbook.Worksheets(3).Range("BC5").Value = TimeValue("00:00:30")
Repeater
End If
If ThisWorkbook.Worksheets(3).Range("BC5").Value > TimeValue("00:00:00") And IsOffline = "Online" Then
ThisWorkbook.Worksheets(3).Range("BC5").Value = ThisWorkbook.Worksheets(3).Range("BC5").Value - TimeValue("00:00:01")
Repeater
End If
End Sub
Solution 1:[1]
In NextTick, if the first If block executes then the second one will also execute (because in the first block you reset BC5)
That should be an If... Else... End If block, not two separate If blocks.
Dim IsOffline As String
Sub Repeater()
Dim RunTimer
IsOffline = ThisWorkbook.Worksheets(3).Range("BC2").Value
If IsOffline = "Online" Then
RunTimer = Now + TimeValue("00:00:01")
Application.OnTime RunTimer, "NextTick"
End If
End Sub
Sub NextTick()
If IsOffline = "Online" Then
With ThisWorkbook.Worksheets(3).Range("BC5")
If .Value <= TimeValue("00:00:00") Then
'Database 'Call is deprecated
.Value = TimeValue("00:00:30")
Else
.Value = .Value - TimeValue("00:00:01")
End If
End With
Repeater
End If
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
