Home > Mobile >  VBA to bold calculated period in email message using WordEditor
VBA to bold calculated period in email message using WordEditor

Time:10-01

I'm writing a vba script to automate a weekly email task, and I'm using WordEditor to insert the text message. In the email message, there are months calculated by function Format(DateAdd("m", -1, Now()), "Mmmm") and I want to highlight them in Bold and red colour. Can someone tell me the code to do it?

Sub EmailAllOpenPOs()

Dim ol As Outlook.Application
Dim mi As Outlook.MailItem
Dim doc As Word.Document
Dim MsgText As String


Set ol = New Outlook.Application
Set mi = ol.CreateItem(olMailItem)

With mi
    .Subject = "Purchase Orders Review & Approval Process (REVIEW & ACTION REQUIRED) as of " & Format(Now(), "d/m/yy")
    .Display
End With

Set doc = mi.GetInspector.WordEditor

MsgText = vbNewLine
doc.Range(0, 0).InsertBefore MsgText

MsgText = "Dear all," & vbNewLine & vbNewLine & _
        "There are some POs related to " & Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm") & " still open." & vbNewLine & vbNewLine & _
        "Could you please review and advise a.s.a.p. if you require finance to accrue them for this month end?"

doc.Range(0, 0).InsertBefore MsgText

Set doc = Nothing

End Sub

CodePudding user response:

Add this before Set doc = Nothing:

Dim formatRng As Word.Range
Set formatRng = doc.Range.Duplicate
With formatRng
    .Find.Execute Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm")
    .Font.Bold = True
    .Font.ColorIndex = wdRed
End With
Set formatRng = Nothing

If you only want to bold and red the month only (without the "and"):

Dim formatRng As Word.Range
Set formatRng = doc.Range.Duplicate
With formatRng
    .Find.Execute Format(DateAdd("m", -1, Now()), "Mmmm") & " and " & Format(Now(), "Mmmm")
    With .Words(1).Font
        .Bold = True
        .ColorIndex = wdRed
    End With
    With .Words(3).Font
        .Bold = True
        .ColorIndex = wdRed
    End With
End With
Set formatRng = Nothing
  • Related