Skip to content

Instantly share code, notes, and snippets.

@ming-chu
Last active March 1, 2018 16:10
Show Gist options
  • Save ming-chu/717a582f6d27d03a80e5db1ece04ccfa to your computer and use it in GitHub Desktop.
Save ming-chu/717a582f6d27d03a80e5db1ece04ccfa to your computer and use it in GitHub Desktop.
vba-count-hours
Function COUNT_HOURS(startEndTime As String)
'Will count the hours between times in format "1230-1500"
'====================================
Dim countHours As Double
countHours = 0
Dim times() As String: times = Split(startEndTime, "-")
Dim arrayCount As Integer: arrayCount = UBound(times) - LBound(times) + 1
Debug.Print "Count" + CStr(arrayCount)
If arrayCount < 2 Then
COUNT_HOURS = 0
'TODO: Prompt error..
Debug.Print "Error, count < 2"
Exit Function
End If
Dim startTime As String: startTime = times(0)
Dim endTime As String: endTime = times(1)
Dim startHour As Integer: startHour = Left(startTime, 2)
Dim startMin As Integer: startMin = Right(startTime, 2)
Dim endHour As Integer: endHour = Left(endTime, 2)
Dim endMin As Integer: endMin = Right(endTime, 2)
Dim totalMins As Integer: totalMins = 0
totalMins = ((endHour * 60) + endMin) - ((startHour * 60) + startMin)
countHours = CDbl(totalMins) / CDbl(60)
COUNT_HOURS = countHours
End Function
Sub Testing()
Debug.Print "1230-1530 count=" + CStr(COUNT_HOURS("1230-1530"))
'0830-1500
Debug.Print "0830-1500 count=" + CStr(COUNT_HOURS("0830-1500"))
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment