Convert dates from short to long(er)

P

Poseur

One of the documents I have to prepare regularly requires
dates spelled out ("March 16, 2006") which takes longer than
3/16/06. So, here's my macro. I post this for 2 reasons:
1. It might be of use to someone else.
2. I love seeing how the really great coders take something
like this and make it more elegant, contract it into a couple
lines of code, and point out the pitfalls.

Public Sub Convert_Dates_From_Short_To_Longer()
Dim rng As Range
Dim res As Boolean
Set rng = ActiveDocument.Range(Start:=0, End:=0)
Do
With rng.Find
.Forward = True
.MatchWholeWord = False
.MatchWildcards = True
.Wrap = wdWrapContinue = True
res = .Execute(FindText:="[0-9]{1,2}/[0-9]{1,2}/
[0-9]{2,4}")
If IsDate(rng.Text) Then
rng.Text = Format(CDate(DateValue
(rng.Text)), "mmm dd, yyyy")
End If
rng.Collapse Direction:=wdCollapseEnd
End With
Loop While res
End Sub
 
J

Jezebel

A couple of suggestions --

1. Your loop structure is more complex than you need. Sufficient is --

Set rng = ActiveDocument.Content
With rng.Find
.MatchWildcards = True
.Wrap = wdFindContinue
.FindText:="[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}"
do while .Execute
rng = ...
Loop
End with


2. There are several gotchas with the date functions. They might not matter
here because you're only dealing with strings that match your Find string,
and you can possibly make assumptions about the format of the dates you're
dealing with. a) IsDate() returns true for a lot of strange strings (eg
"0:0:0") that are not very helpful as dates. b) Your function will come to
grief if you meet non-US dates. Experiment with strings like "12/13/14" and
"13/12/14". Not to mention ISO 8601 format dates - 2014/12/14 - (which
DateValue also handles).


3. This statement ".Wrap = wdWrapContinue = True" is actually saying set
..Wrap to the result of (wdWrapContinue = TRUE), ie FALSE. Even if you use
the correct constant (wdFINDContinue), it's still wrong, because
wdFindContinue is 1 not -1.
 
P

Poseur

1. Your loop structure is more complex than you need.
Sufficient is --

Set rng = ActiveDocument.Content
With rng.Find
.MatchWildcards = True

That's what I thought but I couldn't figure out how to do it
better. Thanks. That's why I post here.
2. There are several gotchas with the date functions. They
might not matter here because you're only dealing with
strings that match your Find string..

Agreed. But since I'm writing the dates, I know what the format
is. The macro is not universally applicable for imported text.
3. This statement ".Wrap = wdWrapContinue = True" is

That was just a typo - copy/pasto.
Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top