Wilfred
Wilfred

Reputation: 29

Configuring module

I have a snippet (Credit: DanteAmor) which serves to countdown and close form. I have userform1 renamed as Question1. See code:‎

The UserForm Code:

‎Private Sub UserForm_Initialize()‎
Label1.Caption = "00:00:30" 'Write the starting number‎
Call CountDown‎
End Sub
‎

Private Sub UserForm_Terminate()
Call CountDown_End
End Sub

‎‎

The Module Code

Sub CountDown()
If Question1.Label1.Caption = "00:00:00" Then
Unload Question1
Exit Sub
End If
Question1.Label1.Caption = Format(TimeValue(Question1.Label1.Caption) - TimeValue("00:00:01"), "hh:mm:ss")
DoEvents
Application.OnTime (Now + TimeValue("00:00:01")), "CountDown"
End Sub

Sub CountDown_End()
On Error Resume Next
Application.OnTime (Now + TimeValue("00:00:01")), "CountDown", , False
End Sub

My Challenge‎

I shall be creating Question 1 to 50. I have just created Question2 but the above module works for Question1 alone. I have done all I could to get the module work with Question2 and subsequent questions but can't seem to fix it. ‎Please can anyone help re-write the above module such that it works with all other Questions?

Thank you.

See Question1 form

Question1 form

Upvotes: 1

Views: 53

Answers (1)

Brian M Stafford
Brian M Stafford

Reputation: 8868

The CountDown logic is hard-coded for Question1. So the challenge is how to remedy this flaw. My first thought was to pass the question as a parameter, unfortunately this does not work when using OnTime. But essentially the same thing can be achieved by defining a UserForm variable in the module:

UserForm

Option Explicit

Private Sub UserForm_Initialize()
   Label1.Caption = "00:00:30"
   Set Question = Me
   Call CountDown
End Sub

Private Sub UserForm_Terminate()
   Call CountDown_End
End Sub

Module

Option Explicit

Public Question As UserForm

Public Sub CountDown()
   If Question.Label1.Caption = "00:00:00" Then
      Unload Question
      Exit Sub
   End If

   Question.Label1.Caption = Format(TimeValue(Question.Label1.Caption) - TimeValue("00:00:01"), "hh:mm:ss")
   DoEvents
   Application.OnTime (Now + TimeValue("00:00:01")), "CountDown"
End Sub

Public Sub CountDown_End()
   On Error Resume Next
   Application.OnTime (Now + TimeValue("00:00:01")), "CountDown", , False
End Sub

Upvotes: 1

Related Questions