jbrandenburg
jbrandenburg

Reputation: 13

Search word document for month/date and replace with different month/date

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

Answers (1)

cxw
cxw

Reputation: 17051

Actually, you don't even need VBA if you don't want to use it --- a wildcard search will do.

  1. Open the Replace dialog, hit More (if necessary), then check Use wildcards.
  2. In the "Find what" box, put 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.
  3. In the "Replace with" box, put the new date.
  4. Hit Replace All.

Bingo! E.g., if MMMM=March, any date in March will be replaced with the new date you specify.

Explanation

  • [ ^s] is a space or nonbreaking space
  • [0-9]{1,2} is either one or two ({1,2}) digits ([0-9]).
  • Similarly, [0-9]{4,4} is exactly four digits.

VBA

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

Related Questions