VBA display current hour

hailstorm

New Member
Joined
Sep 14, 2019
Messages
32
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
 

Some videos you may like

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
L

Legacy 456155

Guest
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
 

Watch MrExcel Video

Forum statistics

Threads
1,123,144
Messages
5,599,978
Members
414,354
Latest member
Flaxarn

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
Top