Reputation: 13
In my new job I'm sending invoices with personalized, dated letters. Each month I go into a word doc for each client and update the date from whatever date we last send an invoice to the date we're sending the current invoice. I know basically nothing about coding, but I have managed to get something together that will search for a month and replace it with a new month. I did this by googling and piecing it together. I have no idea if its good or not, but it works.
Sub Test()
With Selection.Find
.Text = "April"
.Replacement.Text = "May"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
My question is, is there a way to search for a date like "Month DD, YYYY" and replace it with a date of my choosing? Also, it won't necessarily be the same previous date.
Thanks in advance
Upvotes: 1
Views: 568
Reputation: 17051
Actually, you don't even need VBA if you don't want to use it --- a wildcard search will do.
MMMM[ ^s][0-9]{1,2},[ ^s][0-9]{4,4}
, but with the actual month you want in place of MMMM
. It's case-sensitive.Bingo! E.g., if MMMM
=March
, any date in March will be replaced with the new date you specify.
[ ^s]
is a space or nonbreaking space[0-9]{1,2}
is either one or two ({1,2}
) digits ([0-9]
).[0-9]{4,4}
is exactly four digits.For completeness, here it is:
Option Explicit
Option Base 0
Sub Test()
With Selection.Find
.Text = "March[ ^s][0-9]{1,2},[ ^s][0-9]{4,4}" ' ###
.Replacement.Text = "April 1, 2018"
.Forward = True
.Wrap = wdFindContinue
.Format = False
'.MatchCase = False ' ### Not relevant when using wildcards
.MatchWholeWord = False
.MatchWildcards = True ' ###
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
PS- Congratulations on starting out in VBA! Your code looks fine to me - it's pretty close to what you'd get from the macro recorder for the same operation, but cleaner. Two tips you don't need just yet :) — always use Option Explicit
at the top of every module, and Dim
your variables with specific types.
Upvotes: 0