Thursday, September 8, 2011

Count times entered into a document



A user in a Word newsgroup asked how to total the number of times associated with documented sound bites grouped in sections, similar to that shown in the illustration below. The macro below will count all the times in the format HH:MM:SS in the section where the cursor is located.




Sub CountTimes()
'Totals times in the current section
'Times should be in the format HH:MM:SS

Dim sNum As Long
Dim oRng As Range
Dim sText As String
Dim sHr As Long
Dim sMin As Long
Dim sSec As Long

sHr = 0
sMin = 0
sSec = 0
sNum = Selection.Information(wdActiveEndSectionNumber)
Set oRng = ActiveDocument.Range

With oRng.Find
     .ClearFormatting
     .Replacement.ClearFormatting
     .Text = "[0-9]{2}:[0-9]{2}:[0-9]{2}"
     'Look for times in the format 00:00:00
     .Wrap = wdFindStop
     .MatchWildcards = True
     Do While .Execute = True
          sText = oRng.Text
          'To count the whole document, omit the next line
          If oRng.Information(wdActiveEndSectionNumber) = sNum Then
          'Split the found time into three separate numbers
          'representing hours minutes and seconds and add to
          'the previously recorded hours, minutes and seconds

               sHr = sHr + Left(sText, 2)
               sMin = sMin + Mid(sText, 4, 2)
               sSec = sSec + Right(sText, 2)
          'To count the whole document, omit the next line
          End If
     Loop
End With


If sSec > 60 Then 'Divide by 60 and add to the minutes total
     sMin = sMin + Int(sSec / 60)
     sSec = sSec Mod 60 'The remainder is the seconds
End If
If
sMin > 60 Then 'Divide by 60 and add to the hours total
     sHr = sHr + Int(sMin / 60)
     sMin = sMin Mod 60 'The remainder is the minutes
End If
MsgBox sHr & " hours" & vbCr & _
format(sMin, "00") & " Minutes" & vbCr & _
format(sSec, "00") & " Seconds"
End Sub

No comments:

Post a Comment