Converting a timer to show seconds only - vba

I have a timer set as a VB object in a spread sheet. It currently displays as
hh:mm:ss.00. I need it to display as seconds only (no miliseconds or minutes, IE 1:30 should show as 90).
Dim StopTimer As Boolean
Dim Etime As Single
Dim Etime0 As Single
Dim LastEtime As Single
Private Sub CommandButton1_Click()
StopTimer = False
Etime0 = Timer() - LastEtime
Do Until StopTimer
Etime = Int((Timer() - Etime0) * 100) / 100
If Etime > LastEtime Then
LastEtime = Etime
Label1.Caption = Format(Etime / 86400, "hh:mm:ss.") & Format(Etime * 100 Mod 100, "00")
DoEvents
End If
Loop
End Sub
Private Sub CommandButton2_Click()
StopTimer = True
Beep
With New MSForms.DataObject
.SetText Label1.Caption
.PutInClipboard
End With
End Sub
Private Sub CommandButton3_Click()
StopTimer = True
Etime = 0
Etime0 = 0
LastEtime = 0
Label1.Caption = "00"
End Sub
I'm sure I'm simply overlooking something obvious but I'm not overly familiar with timers and formatting.

Please refer this link:
Convert HH:MM:SS string to seconds only in javascript
And try this:
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
console.log(seconds);

This is probably the easiest and the most comprehensive way, as a minute has 60 seconds and one hour has 3600 seconds.
Thus 1 minute and 30 seconds would be 0*3600 + 1*60 + 30:
Public Sub TestMe()
Dim myTime As Date
myTime = TimeSerial(0, 1, 30)
Debug.Print Hour(myTime) * 3600 + Minute(myTime) * 60 + Second(myTime)
End Sub
It takes 1:30 and it returns 90. You may consider writing a separate function like this one as well:
Public Function TimeToSeconds(Optional hours As Long = 0, _
Optional minutes As Long = 0, _
Optional seconds As Long = 0) As Long
TimeToSeconds = hours * 3600 + minutes * 60 + seconds
End Function

Related

Countdown timer with time format(00:00:00) in vba access

I am creating Access db which needs auto close the db using timer count down. for example, if I give 5 min then it should start count down displaying this time format 00:04:59
I have found several pieces of tips checking the web, but did not manage to fit the pieces to one working piece.
Below is working perfect. but in output i can see only min and sec 0:00. How to add code for hours as well (format 00:00:00)? I tried to add hours but it is not working
Public Loops As Integer
Private Sub Form_Load()
Me.TimerInterval = 1000
Form_Timer
End Sub
Private Sub Form_Timer()
Static StartTime As Date
Dim SecondsToCount As Integer
SecondsToCount = 15 'Set this variable to the total number of seconds to
count down
If Loops = 0 Then StartTime = Time
Min = (SecondsToCount - DateDiff("s", StartTime, Time)) \ 60
Sec = (SecondsToCount - DateDiff("s", StartTime, Time)) Mod 60
Me.TimeLeft.Caption = "Form will close in " & Min & ":" & Format(Sec,"00")
Loops = Loops + 1
If Me.TimeLeft.Caption = "Form will close in 0:00" Then
DoCmd.Close acForm, Me.Name
End If
End Sub
Use a textbox for display, Timer to get a better resolution, and a TimerInterval of 100 for a closer match.
Complete code-behind module of the form:
Option Compare Database
Option Explicit
Private WatchTime As Date
Private Sub Form_Load()
' Specify count down time.
Const CountDownSeconds As Long = 15
WatchTime = DateAdd("s", CountDownSeconds, Now)
Me!txtCount.Value = WatchTime
Me.TimerInterval = 100
End Sub
Private Sub Form_Timer()
Const SecondsPerDay As Long = 86400
Dim TimeLeft As Date
TimeLeft = CDate(WatchTime - Date - Timer / SecondsPerDay)
Me!txtCount.Value = TimeLeft
If TimeLeft <= 0 Then
Me.TimerInterval = 0
MsgBox "Time ran out!", vbExclamation, "Exit"
DoCmd.Close acForm, Me.Name
End If
End Sub

MS Access weird numbers

I receive weird numbers from a function in VBA.
I have Continuous Forms where is a button from which user can manipulate sum of hours in a text box. This text box is located in Form Footer.
My code goes like this:
Private Sub Option39_Click()
Dim time As Double
'calculate time to format
time = 25 / 24
If Option39.Value = True Then
Debug.Print dblTotal
dblTotal = dblTotal + time
Debug.Print dblTotal
Me.txtTotalTeamTotal = FormatUnlimitedHours(dblTotal)
Debug.Print dblTotal
Else
dblTotal = dblTotal - time
Me.txtTotalTeamTotal = FormatUnlimitedHours(dblTotal)
End If
End Sub
from debug.print i receive these values
3,66611111111111
4,70777777777778
112,986666666667
which I don't understand why the dblTotal change its value from 4,70777777777778 to 112,986666666667 Why was the number changed?
FormatUnlimitedHours() function is defined like this:
Public Function FormatUnlimitedHours(time As Variant) As Variant
'function that can have unlimited number of hours in hh:mm:ss format
Dim comma As Integer
Dim hours As Variant
Dim minutes As Variant
'switch to hours format
time = time * 24
If time > 23 Then
comma = InStr(time, ",") - 1
If Not comma < 0 Then
minutes = "0," & Mid(time, comma + 2, Len(time) - comma + 1)
minutes = format(minutes / 24, "hh:mm:ss")
hours = CDbl(Left(time, comma)) + CDbl(Left(minutes, InStr(minutes, ":") - 1))
FormatUnlimitedHours = hours & ":" & Mid(minutes, InStr(minutes, ":") + 1, 5)
Exit Function
Else
'for whole numbers
FormatUnlimitedHours = time & ":00:00"
Exit Function
End If
End If
FormatUnlimitedHours = format(time / 24, "hh:mm:ss")
End Function
initial value of dblTotal is defined when the form is loaded
Private Sub Form_Load()
dblTotal = DSum("sumOfTotalTime", "QueryTime")
End Sub
Tim Williams has answered your question. However, you should never handle date and time as anything else than DateTime. It only complicates matters.
For example, comma is not the decimal separator in most English speaking countries, and the "base" type of DateTime is Double, so normally it makes no difference to convert back and forth between DateTime and Double.
Here's an example of a similar function following these rules - which also makes it a lot simpler:
Public Function FormatHourMinuteSecond( _
ByVal datTime As Date, _
Optional ByVal strSeparator As String = ":") _
As String
' Returns count of days, hours, minutes, and seconds of datTime
' converted to hours, minutes, and seconds as a formatted string
' with an optional choice of time separator.
'
' Example:
' datTime: #10:03:55# + #20:01:24#
' returns: 30:05:19
'
' 2014-06-17. Cactus Data ApS, CPH.
Dim strHour As String
Dim strMinuteSec As String
Dim strHours As String
strHour = CStr(Fix(datTime) * 24 + Hour(datTime))
' Add leading zero to minute and second count when needed.
strMinuteSec = Right("0" & CStr(Minute(datTime)), 2) & strSeparator & Right("0" & CStr(Second(datTime)), 2)
strHours = strHour & strSeparator & strMinuteSec
FormatHourMinuteSecond = strHours
End Function
Example:
? FormatHourMinuteSecond(25 / 24)
25:00:00

VBA Dateadd Format - Need In Total Minutes

I have a userform in Microsoft Excel that I want to use as a stopwatch. However the format of "hh:mm" does not allow it to go above 23:59 as it goes back to 00:00
Private Sub SpinButton2_SpinUp()
If InsertEvent.TextBox1 = vbNullString Then
InsertEvent.TextBox1 = "00:00"
Else
InsertEvent.TextBox1.Value = Format(DateAdd("n", 1, InsertEvent.TextBox1.Value), "hh:mm")
'InsertEvent.TextBox1.Value = TimeValue("mm:ss")
'InsertEvent.TextBox1.Value = Format(InsertEvent.TextBox1.Value, "hh:mm")
End If
End Sub
Is there anyway to format this so that it can work as a clock of total minutes? Ideally I need it to go to about 125 minutes or so (125:00) but it doesn't matter if it is unlimited.
You can't use the built in Date/Time functions for this as you want a representation that is not a Date/Time.
Assuming you want to read the spinner value into the textbox:
Private Sub SpinButton2_SpinUp()
Dim minutes As Integer: minutes = Val(InsertEvent.SpinButton2.Value)
Dim hh As Integer: hh = minutes \ 60
Dim mm As Integer: mm = minutes - (hh * 60)
InsertEvent.TextBox1.Text = Format$(hh, "00") & ":" & Format$(mm, "00")
End Sub
To use a manually entered value from the textbox as the starting up/down point you need to re-parse "hh:mm" back to minutes, for example in the textbox Exit event:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If (IsNumeric(TextBox1.Text)) Then
'// entering a number only assumes its minutes
SpinButton2.Value = TextBox1.Text
Exit Sub
End If
Dim hhmm() As String: hhmm = Split(TextBox1.Text, ":")
If (UBound(hhmm) = 1) Then
If (IsNumeric(hhmm(0)) And IsNumeric(hhmm(1))) Then
SpinButton2.Value = (hhmm(0) * 60) + hhmm(1)
Exit Sub
End If
End If
SpinButton2.Value = 0
End Sub
(Should add error checking for overflow/exceeding the spinners .Max property)

How can I get hh:mm:ss to display in just seconds in vb.net

I have tried to get vb.net to display the running time which worked in the format hh:mm:ss. I want to get it to display in just seconds could I get help?
So for example if it was 10:00:00 am, then that would be 10 * 60 * 60. However the time would automatically continue and if say the time was 10:19:23 am then what would I do?
My code:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label2.Text = Format(Now, "HH:mm:ss")
End Sub
Private Function GetSeconds(ByVal timestamp As DateTime) As Integer
Dim timespan As TimeSpan = Now - timestamp
Return (timespan.TotalSeconds)
End Function
Here are few ways to get the time of day in seconds:
Dim a As Double = Now.TimeOfDay.TotalSeconds ' 39715.561210299995
Dim b As Long = TimeOfDay.Ticks \ 10000000 ' 39715
Dim c As Double = TimeOfDay.ToOADate * 24 * 60 * 60 ' 39715.000000000007
Dim d As Double = (Now.ToOADate Mod 1) * 24 * 60 * 60 ' 39715.000000000007

How to get a DateDiff-Value in milliseconds in VBA (Excel)?

I need to calculate the difference between two timestamps in milliseconds.
Unfortunately, the DateDiff-function of VBA does not offer this precision.
Are there any workarounds?
You could use the method described here as follows:-
Create a new class module called StopWatch
Put the following code in the StopWatch class module:
Private mlngStart As Long
Private Declare Function GetTickCount Lib "kernel32" () As Long
Public Sub StartTimer()
mlngStart = GetTickCount
End Sub
Public Function EndTimer() As Long
EndTimer = (GetTickCount - mlngStart)
End Function
You use the code as follows:
Dim sw as StopWatch
Set sw = New StopWatch
sw.StartTimer
' Do whatever you want to time here
Debug.Print "That took: " & sw.EndTimer & "milliseconds"
Other methods describe use of the VBA Timer function but this is only accurate to one hundredth of a second (centisecond).
If you just need time elapsed in Centiseconds then you don't need the TickCount API. You can just use the VBA.Timer Method which is present in all Office products.
Public Sub TestHarness()
Dim fTimeStart As Single
Dim fTimeEnd As Single
fTimeStart = Timer
SomeProcedure
fTimeEnd = Timer
Debug.Print Format$((fTimeEnd - fTimeStart) * 100!, "0.00 "" Centiseconds Elapsed""")
End Sub
Public Sub SomeProcedure()
Dim i As Long, r As Double
For i = 0& To 10000000
r = Rnd
Next
End Sub
GetTickCount and Performance Counter are required if you want to go for micro seconds..
For millisenconds you can just use some thing like this..
'at the bigining of the module
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
'In the Function where you need find diff
Dim sSysTime As SYSTEMTIME
Dim iStartSec As Long, iCurrentSec As Long
GetLocalTime sSysTime
iStartSec = CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds
'do your stuff spending few milliseconds
GetLocalTime sSysTime ' get the new time
iCurrentSec=CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds
'Different between iStartSec and iCurrentSec will give you diff in MilliSecs
If Timer() precision is enough then you can just create timestamp by combining date and time with milliseconds:
Function Now2() As Date
Now2 = Date + CDate(Timer / 86400)
End Function
To calculate the difference between two timestamps in milliseconds you may subtract them:
Sub test()
Dim start As Date
Dim finish As Date
Dim i As Long
start = Now2
For i = 0 To 100000000
Next
finish = Now2
Debug.Print (finish - start) & " days"
Debug.Print (finish - start) * 86400 & " sec"
Debug.Print (finish - start) * 86400 * 1000 & " msec"
End Sub
Actual precision of that method is about 8 msec (BTW GetTickCount is even worse - 16 msec) for me.
You can also use =NOW() formula calcilated in cell:
Dim ws As Worksheet
Set ws = Sheet1
ws.Range("a1").formula = "=now()"
ws.Range("a1").numberFormat = "dd/mm/yyyy h:mm:ss.000"
Application.Wait Now() + TimeSerial(0, 0, 1)
ws.Range("a2").formula = "=now()"
ws.Range("a2").numberFormat = "dd/mm/yyyy h:mm:ss.000"
ws.Range("a3").formula = "=a2-a1"
ws.Range("a3").numberFormat = "h:mm:ss.000"
var diff as double
diff = ws.Range("a3")
Apologies to wake up this old post, but I got an answer:
Write a function for Millisecond like this:
Public Function TimeInMS() As String
TimeInMS = Strings.Format(Now, "HH:nn:ss") & "." & Strings.Right(Strings.Format(Timer, "#0.00"), 2)
End Function
Use this function in your sub:
Sub DisplayMS()
On Error Resume Next
Cancel = True
Cells(Rows.Count, 2).End(xlUp).Offset(1) = TimeInMS()
End Sub
Besides the Method described by AdamRalph (GetTickCount()), you can do this:
Using the QueryPerformanceCounter() and QueryPerformanceFrequency() API Functions
How do you test running time of VBA code?
or, for environments without access to the Win32 API (like VBScript), this:
http://ccrp.mvps.org/ (check the download section for the "High-Performance Timer" installable COM objects. They're free.)