You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA使用WordEditor将邮件内计算得出的月份设置为加粗红色

实现思路

你通过WordEditor操作邮件正文本质是操作Word文档对象,不需要一次性插入全部正文,拆分插入步骤,在插入月份文本后立刻选中对应范围修改格式即可,修改后的完整代码如下:

Sub EmailAllOpenPOs()
    Dim ol As Outlook.Application
    Dim mi As Outlook.MailItem
    Dim doc As Word.Document
    Dim insertRng As Word.Range
    Dim lastMonth As String, currMonth As String
    
    ' 提前计算好两个月份文本
    lastMonth = Format(DateAdd("m", -1, Now()), "Mmmm")
    currMonth = Format(Now(), "Mmmm")
    
    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
    ' 初始化插入范围为文档开头
    Set insertRng = doc.Range(0, 0)
    
    ' 插入开头空行
    insertRng.InsertBefore vbNewLine
    insertRng.Collapse wdCollapseStart ' 光标移到最开头准备插入正文
    
    ' 插入正文开头部分
    insertRng.Text = "Dear all," & vbNewLine & vbNewLine & _
                    "There are some POs related to "
    insertRng.Collapse wdCollapseEnd ' 光标移到刚插入内容的末尾
    
    ' 插入上个月,设置格式
    insertRng.Text = lastMonth
    insertRng.Bold = True
    insertRng.Font.Color = wdColorRed
    insertRng.Collapse wdCollapseEnd
    
    ' 插入连接文本
    insertRng.Text = " and "
    insertRng.Collapse wdCollapseEnd
    
    ' 插入当月,设置格式
    insertRng.Text = currMonth
    insertRng.Bold = True
    insertRng.Font.Color = wdColorRed
    insertRng.Collapse wdCollapseEnd
    
    ' 插入剩余正文
    insertRng.Text = " 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?"
    
    ' 释放对象
    Set insertRng = Nothing
    Set doc = Nothing
    Set mi = Nothing
    Set ol = Nothing
End Sub

注意事项

如果你没有提前在VBA编辑器的「工具-引用」中勾选「Microsoft Word [版本号] Object Library」,需要把代码中Word相关的常量替换为对应数值即可用后期绑定运行,不需要提前引用库:

  • wdCollapseStart 替换为 0
  • wdCollapseEnd 替换为 1
  • wdColorRed 替换为 255

内容的提问来源于stack exchange,提问作者Hazel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:15:02