I have 2 strings, strStartTime and strEndTime.
strStartTime = "12:32:54"
strEndTime = "12:33:05"
I want to find out how many seconds elapsed between strStartTime and strEndTime so I did this:
Dim dtDuration as date
dtDuration = DateDiff("s", CDate(strStartTime), CDate(strEndTime))
The result I get is dtDuration = "#1/10/1900#" in the Locals watch window.
Why does this happen? How do I get dtDuration to equal 11 for the 11 seconds that elapsed between the start and end times?
Just change variable type to Long:
Dim dtDuration as Long
VBA converts numerical results of DateDiff functions into variable with date type.
Related
I have a VBA user form which when I press save after input data it writes to a spread sheet and set my time and date to Now() that is being written to a spread sheet where I split the now() value into time and date, when I read it back I get the date but my time in decimal format I would like to convert that decimal number back to time what is the formula for that thank you in advance my decimal number is something like '0.12425576899' so far I found this but it converts that to '00:the minutes on the double:00' here is the code
Public Function FromDecimalTime(ByVal t As Double) As Date
FromDecimalTime = TimeSerial(0, Fix(t), (t - Fix(t)) * 60)
End Function
The following will convert the Double into the Date Format. In order to only show the time portion of the date format, use the Format function:
Sub trythis()
Dim t As Double
t = Now()
Debug.Print CDate(t)
Debug.Print Format(t, "hh:mm:ss")
End Sub
I am trying to get values from one of the column from excel and i am facing strange issue that i cannot overcome so far.
Excel cells text we working on
Column format is set to: [h]:mm:ss so means hours could exceed 12/24.
When i am getting that values they are in double format as excel probbaly stores it in that way therefore i decided to write function to convert it back again to hours, minutes and seconds so i did that function:
Public Shared Function parseExcelHour(cellInput As String) As String
Dim excelHour As Double = 0
Dim hour As Integer
Dim min As Integer
Dim sec As Integer
Try
excelHour = [Double].Parse(cellInput)
Catch
End Try
sec = CInt((excelHour * 1440 * 60) Mod 60)
min = CInt((excelHour * 1440) Mod 60)
'mod (%) takes only the remainder as an int (if 5/4 = 1.25 , % only takes the number 1 that cannot be divided into an integer)
hour = CInt((excelHour * 1440) / 60)
' with the int cast you get only an integer.
Return hour & ":" & min & ":" & sec
End Function
However when i see the results, they are vary between excel and what i get after conversion. For three of them hours are either -1 or +1 if you compare. Also in one case we have additional + 1 minute. I suppose there is wrong hour calculation but i could be in wrong. See on screeshoot:
Results
Does anyone knows why i got those differences? Is that because i am missing something within my method or something else.
Excel stores a full Datetime equivalent as one double. The part before the decimal point is the days (since 1.1.1900; 1.1.1904 on Mac; note the bug that 1900 is faultily cosnider a leap year in Excel).
The part after is the time of the day, wich is what you apparently want:
https://stackoverflow.com/a/981865/3346583
What you are seeing in excel is meerely a ToString Foramting of the double value. Same way DateTime.ToString() would give you a string representation of whatever value is actually stored (most often a realy big unsigned int, with the ticks since a date).
A difference in full hours sounds like it might be a Timezone issue. But I am not aware that Excel stores Timezones in the first place (or what default timezone it asumes).
I'm working on a problem where I need to determine the total time my program takes to execute. First line of code needs to write the current "Start time" and last lines of code need to write the current "End time". Then I'm subtracting "Start time" - "End Time" = Total Time.
I'm confused how I would use the FORMAT() function within VBA on the value of C2 to convert into seconds? Is there an other function that would work better than FORMAT? Basically I'm confused about Excel's Date Serial values and what they represent.
Code is below
EDIT: Thanks for the responses everyone. Both answers below work for what I'm trying to do.
sub ExecutionTime()
Worksheets("Table").Range("A2").Value = Now()
'All my executable code goes here. It's a relatively small program compiling a table so it
runs very quick.
Worksheets("Table").Range("B2").Value = Now()
Worksheets("Table").Range("C2").Value = Worksheets("Table").Range("A2").Value - Worksheets("Table").Range("B2").Value
end Sub
Do not use a Date data member or the Now method to analyze run time of your program. Instead, the Timer function is the most appropriate solution as it returns a Single representing seconds. It will require no type conversion and yields a more accurate result than an integer amount of seconds.
Using LimaNightHawk's answer as a template as you should be storing these in local variables instead of writing directly to the worksheet.
Dim startTime as Single
startTime = Timer()
' Do stuff
Dim endTime as Single
endTime = Timer()
Dim runTime as Single
runTime = endTime - startTime
Results should be written at the end of the routine.
With Worksheets("Table")
.Range("A2").Value = startTime
.Range("B2").Value = endTime
.Range("C2").Value = runTime
End With
Documentation on the timer function
In the first line of your program get the date (no need to format):
Dim startTime as Date
startTime = Now()
At the end of your program, get the date again:
Dim endTime as Date
endTime = Now()
Then use the DateDiff
Dim timeInSeconds as long
timeInSeconds = DateDiff("s", startTime, endTime)
DateDiff() is what you are looking for. The "s" defines that you are looking for the difference in seconds.
Worksheets("Table").Range("C2").Value = DateDiff("s", Worksheets("Table").Range("A2").Value, Worksheets("Table").Range("B2").Value)
EDIT: http://www.likeoffice.com/28057/excel-date to learn more about working with dates and times in Excel VBA. It is important to understand that dates work differently within the context of VBA, and have their own unique set of syntax functions for manipulating.
2nd EDIT: A cleaner version of this would be:
StartDateTime = Now()
'Run Code
Worksheets("Table").Range("C2").Value = DateDiff("s", StartDateTime, Now())
There's a few ways you can use VBA to format cells / variables.
In no particular order, firstly you can format ranges with the NumberFormat property which can be applied like so:
Worksheets("Table").Range("C2").Value = Now()
Worksheets("Table").Range("C2").NumberFormat = "ss"
The other way is that you could format Now() using the Format() function:
Worksheets("Table").Range("C2").Value = Format(Now(), "ss")
See the documentation from Microsoft to implement different formats:
NumberFormat: http://msdn.microsoft.com/en-us/library/office/ff196401%28v=office.15%29.aspx
Format: http://msdn.microsoft.com/en-us/library/office/gg251755%28v=office.15%29.aspx
How i generally go about bragging my process time to user
Sub Process()
Dim startTime as Date
Dim endTime as Date
startTime = Now
'Logic for what your process must do
endTime = Now
MsgBox "Process completed in : " & Format(endTime - startTime, "hh:mm:ss")
End Sub
I am trying to make a spreadsheet to calculate my hours for the week. The problem I am having is the DateDiff function only returns integers so I am getting incorrect results.
Function CalculateHoursDay(strStart As String, strEnd As String, intLunch As Integer) As Double
Dim dblHours As Double
dblHours = DateDiff("h", strStart, DateAdd("h", 12, strEnd)) - intLunch
CalculateHoursDay = dblHours
End Function
If I call the function with "7:00", "2:45", .5 then I get 7 back when I need 7.25. In fact I get 7 also for "7:00", "2:45", 0 so you can see the decimal value is getting truncated. I add 12 hours so times can be easily entered without regard for AM, PM or military time since over 99% (if not 100%) of the time the times will be AM for start time and PM for end time.
I am expecting to get 7.25 from the function with the stated parameters. Any suggestions?
Alex provided the correct answer and tbur also pointed out a bug that would've surfaced as soon as I applied Alex's solution.
Function CalculateHoursDay(strStart As String, strEnd As String, dblLunch As Double) As Double
Dim dblHours As Double
'"n" refers to minutes.
dblHours = (DateDiff("n", strStart, DateAdd("h", 12, strEnd)) / 60) - dblLunch
CalculateHoursDay = dblHours
End Function
How do I assign each value between a colon into a new variable? So 08:10:20 Would be hours,minutes and Seconds In VB.NET?
So
Hours would be equal to 8
Minutes would be equal to 10
Seconds would be equal to 20
The general way to parse a delimited string like that would be do do something like this:
Dim parts() As String = value.Split(":"c)
Dim hours As Integer = Integer.Parse(parts(0))
Dim minutes As Integer = Integer.Parse(parts(1))
Dim seconds As Integer = Integer.Parse(parts(2))
However, if what you really want is a Date object, then you could just do this:
Dim d As Date = Date.ParseExact(value, "HH:mm:ss", CultureInfo.InvariantCulture)
The "HH" means 24-hour time. If you want 12-hour time, use lower-case ("hh").