View Single Post
  #23  
Old August 1st, 2004, 05:05 AM
Myrna Larson
external usenet poster
 
Posts: n/a
Default How to calculate days:Hours:Minutes:

Here is modified code that will handle more than one range, i.e. you could
write

=AverageTimes(J2:J83,J90:J400,"23 Days, 5 Hr, 6Min")

If any of the arguments are not cells containing text in the format you
specified, or literal text in that format, those cells/arguments are treated
as 0. You must specify all 3 pieces, even if the number is 0, i.e. "5 Hr, 10
Min" is illegal -- it has to be "0 Days, 5 Hr, 10 Min".

But I allowed "Day" as well as "Days", it's not case-sensitive, and it's not
fussy about the number or position of spaces [e.g. you have a space before
Days and Hr, but not before "Min"])

Note that the AverageTime function converts each argument to a number, totals
and averages them, and converts the average into the above format.

In my first reply, I explained how to get the code into your workbook. Others
have provided the same information. Good luck!

'~~~~~~~~~~~~~~~~~~~~~~~~~
Option Explicit
Option Base 0

Function AverageTime(ParamArray Durations() As Variant) As String
Dim C As Range
Dim Dur As Double
Dim i As Long
Dim N As Long
Dim Total As Double

N = 0
For i = 0 To UBound(Durations)
'arguments must be a range (1 or more cells) or literal text
Select Case TypeName(Durations(i))
Case "Range"
For Each C In Durations(i).Cells
'ParseDuration will return False if
'the value isn't text in the proper format
If ParseDuration(C.Value, Dur) Then
Total = Total + Dur
N = N + 1
End If
Next C
Case "String"
If ParseDuration((Durations(i)), Dur) Then
Total = Total + Dur
N = N + 1
End If
End Select
Next i

If Total 0 And N 0 Then
AverageTime = ConvertToText(Total / N)
Else
AverageTime = ConvertToText(0)
End If

End Function

Private Function ParseDuration(vDuration As Variant, _
nDuration As Double) As Boolean
Dim Components() As String
Dim Divisors As Variant
Dim i As Long
Dim N As Long
Dim Txt As String

nDuration = 0
ParseDuration = False

If TypeName(vDuration) "String" Then
Exit Function
Else
Txt = CStr(vDuration) 'put it into a string
Txt = LCase$(Txt) 'convert to lower case
Txt = Replace(Txt, " ", "") 'remove the spaces

'check for text 'Days,' 'Hr,' and ending with Min
If (Txt Like "*days,*hr,*min") = False Then
If (Txt Like "*day,*hr,*min") = False Then
Exit Function
End If
End If
End If

Divisors = Array(1, 24, 1440)

Components() = Split(vDuration, ",")
N = UBound(Components())
'require all 3 pieces to be there
If N 2 Then Exit Function

For i = 0 To N
nDuration = nDuration + Val(Components(i)) / Divisors(i)
Next i

ParseDuration = True
End Function

Function ConvertToText(D As Double) As String
ConvertToText = Format$(Fix(D)) & " Days, " _
& Format$(Hour(D)) & " Hrs, " _
& Format$(Minute(D)) & " Min"
End Function

'~~~~~~~~~~~~~~~~~~~~~~~~~