VBA display current hour

hailstorm

New Member
Joined
Sep 14, 2019
Messages
34
Hello there,

I have this simple code running which shows me the date and hour when i first open my userform, the problem is that i want the hour to keep updating as long as the user remains with the form open. How can i do that?

VBA Code:
Private Sub UserForm_Initialize()

data = Date
hora = Time

data.Enabled = True
hora.Enabled = True

End Sub
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
One way is to use Application.OnTime. Another is to use an API timer, which is my preference, but some people think it's too risky.
Here is an example using OnTime.

In a static module:
VBA Code:
Option Explicit

Private CallBackRef As Object
Private NextTick As Date
Private NumSeconds As Long

Sub StartTimer(CallBackThis As Object, NumberOfSeconds As Long)
    Set CallBackRef = CallBackThis 
    NumSeconds = NumberOfSeconds
    TickTock
End Sub

Sub TickTock()
    NextTick = Now + TimeSerial(0, 0, NumSeconds)
    Application.OnTime NextTick, "TickTock"
    CallBackRef.Timer
End Sub

Sub StopTimer()
    Set CallBackRef = Nothing
    Application.OnTime NextTick, "TickTock", , False
End Sub

In your userform:
VBA Code:
Option Explicit

Private Const NumberOfSeconds = 1 'every second

Private Sub UserForm_Initialize()
    data.Enabled = True
    hora.Enabled = True
    StartTimer Me, NumberOfSeconds
End Sub

Private Sub UserForm_Terminate()
    StopTimer
End Sub

Public Sub Timer()
    data = Date
    hora = Time
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,905
Messages
6,122,178
Members
449,071
Latest member
cdnMech

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top