imh0tep
imh0tep

Reputation: 98

Manipulating numbers obtained from a VBA search

I'm trying to craft a script in Word that will allow me to programmatically update times stored in a word document as minutes and seconds. The times are written like this, [01:10] and I would like to find each number, and increment it by a specific, consistent number of minutes and seconds.

I am able to find the timecodes with the following code, but can't figure out how I can convert them into numbers that I can then manipulate and plug back into the document. Any help would be appreciated!

Sub findreplace()
Dim objWdDoc As Document
Set objWdDoc = ActiveDocument
Dim objWdRng As Range
Set objWdRng = objWdDoc.Content
With objWdRng.Find
    .ClearFormatting
    .Text = "\[([0-9][0-9]):([0-9][0-9])\]"
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    If .Execute Then
        Do While objWdRng.Find.Found = True
        .Text = "[0-9][0-9]"
        If .Execute Then
            'Do something here!!
        End If
        Loop
    End If
End With
Set objWdRng = Nothing
End Sub

Upvotes: 1

Views: 51

Answers (1)

Amen Jlili
Amen Jlili

Reputation: 1944

As per your comment, here's a sub in which you supply the time and the seconds that you want to add and it will debug.print the time in the MM:SS format.

Sub Main()
Dim T As Date 
T = #1:24:00 PM# ' <- Your time goes there 
Dim MyTime As String
Dim Seconds As Long: Seconds = 85 ' Seconds to add
MyTime = Format(DateAdd("s", Seconds, T), "mm:ss")
Debug.Print (MyTime)
End Sub

Example: Added 100 seconds to the date above, see the output below (My French locale has a 24 hours format so don't mind that.)

enter image description here

Edit: as per your comment, here's a function that you can call it from any sub.

Function AddSeconds(T As date, Seconds as Long) As String
Dim MyTime As String: MyTime = ""
MyTime = Format(DateAdd("s", Seconds, T), "mm:ss")
AddSeconds = MyTime
End Sub

Please:

  1. Be aware that when you call the function, you need to supplement the correct argument format of a time like the following example:

    MyNewTime = AddSeconds(#3:25:15 AM#,15)

  2. It will return a string datatype and not a Date so MyNewTime must be a string or a variant.

Upvotes: 1

Related Questions