I'm trying to make a macro in Microsoft Word 2013 using VBA to add leading zeroes to dates (mainly dates and months)
So from 4/6/2004 to 04/06/2004 And 5/11/2005 to 05/11/2005
I tried to use a variation of the answer here but it endlessly loops on the first date: http://answers.microsoft.com/en-us/office/forum/office_2010-word/macro-to-convert-date-format-in-a-document/20539af7-a961-499f-9e85-22af8f4c3c58?auth=1
Sub ConvertDateFormat()
Dim FoundOne As Boolean
Selection.HomeKey Unit:=wdStory, Extend:=wdMove
FoundOne = True ' loop at least once
Do While FoundOne ' loop until no date is found
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Forward = True
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceNone
' check that the find is a date
If IsDate(Selection.Text) Then
Selection.Text = Format(Selection.Text, "dd/mm/yyyy")
Selection.Collapse wdCollapseEnd
Else ' not a date - end loop
FoundOne = False
End If
Loop
End Sub
Try this and learn what I have changed.
The art of MS-word find and replace is in Range, collapse and loops(for and do while)
Working fine on Win-7pro, 64, office 2010, 32
Sub ConvertDateFormat()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,2})[/]([0-9]{1,2})[/]([0-9]{4})"
.Format = True
.Wrap = wdFindStop
.Forward = True
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If IsDate(.Text) Then
.Text = Format(.Text, "dd/mm/yyyy")
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.