Saturday 1 December 2018

Create a Stopwatch in Excel Using Excel VBA

Step 1: Select a desired range of cells and merge them.


Step 2: Type "00:00:00" to the cell and format it according to the desired mode.


Step 3: Insert command buttons. Go to "Developer" tab, click "Insert" and look for command button under "ActiveX Controls" and label the button as "Start". To label a command button, the guideline is shown under the "Remark" right after Step 4. 



Step 4: Repeat Step 3 by creating and designing another 2 command buttons and label them as "Stop", and "Reset" respectively.


*Remark: To design those buttons, can click "Properties".



Step 5: Type the following codes to Visual Basic.

Private a As Boolean

Private Sub CommandButton1_Click()
a = True
Do While a
Application.Wait (Now + #12:00:01 AM#)
DoEvents
Sheet3.Cells(5, "H") = Format(DateAdd("s", 1, Sheet3.Cells(5, "H")), "hh:mm:ss")
Loop
End Sub

Private Sub CommandButton2_Click()
a = False
End Sub

Private Sub CommandButton3_Click()
Sheet3.Cells(5, "H") = "00:00:00"
End Sub


*Remark:
1. "Do While ... Loop" is to create an infinite repeating process until it is interrupted (where "a" is set to "False").
2. "Application.Wait (Now + #)" creates a pause of # seconds long. As in the example above, #12:00:01 AM# is one second long.
3. "DoEvents" is used to ensure Excel remains responsive, i.e. the change in time is shown (updated) on the select cells. 
4. Sheet#.Cells(#, "#") - all # have to change to the correct numbers or characters.
5. In the "DateAdd" function, "s" is a unit measure for "second". Other unit measures include: "yyyy" for year, "q" for quarter, "m" for month, "y" for day of year, "d" for day, "w" for weekday, "ww" for week, "h" for hour, and "n" for minute. (Source: Microsoft, 2018. DateAdd function. https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dateadd-function)


If you need a visual or audio aid. kindly watch the below video. Hope it helps.