How to Create a Count Down Timer
If you want to close a form that there is no action taken by the user in certain time frame you can set the counter to count down by second. If the timer is reaching the set amount of seconds then the command will take an action. For this example, I want to put a count-down timer on my Login form. If the user does not login in 1 minute then the Access will close. I will show how to in the steps below.
Step #1 Set Global variable
Declare a form Global variable at the top of VBA of the current form to hold the seconds expired since Form was opened. Set TimeCount as Long.
Option Compare Database
‘Declare a Form Global variable to hold the
‘seconds expired since Form was opened.
Dim TimeCount As Long
Step #2 Add a text box
Open the design view of the form you want to add a text box for a counter. You can delete a label of textbox and leave only the text box and name it “txtCounter.” You can format the font, size, or color of your textbox if you want.
Step #3 Set Timer when Form is Opened
We need to set the timer interval when form is loaded under the On Open Event Procedure in Property Sheet. Set TimerInterval = 1,000 since 1,000 milliseconds (tics) = 1 second.
Private Sub Form_Open(Cancel As Integer)
‘Set the Form’s Timer to 1 second intervals (1000 tics = 1 Second)
Me.TimerInterval = 1000
Step #4 Write code on the Timer Event
Also we need to write a count-down counter under the On Timer Event Procedure. In this example, I will set time frame for 1 minute or 60 seconds. The counter will increment by 1 and display the value on the text box “txtCounter” as 60- Counter. If the counter is 10 then 50 will be displayed on the text box. I also add If Statement to display a number in red color when displayed 20 or less as shown on the picture below.
Private Sub Form_Timer() 'Increment the TimerCount variable by 1 TimeCount = TimeCount + 1 'Display the current seconds remaining in the 'text box corner of form Me.txtCounter.Value = 60 - TimeCount 'If the Seconds Counter (TimerCount) is now equal 'to 40 seconds then the text color changed to Red If TimeCount = 40 Then Me.txtCounter.ForeColor = vbRed End If If TimeCount = 61 Then 'Close the Access Program when the counter is equal to 61 seconds DoCmd.Quit acQuitSaveAll End If End Sub