使用文本和图像填充邮件项目

时间:2015-03-25 22:33:21

标签: excel vba excel-vba word-vba

我在Excel VBA中有以下代码:

Sub CreateEmailAndSend()

    Dim outApp As Object
    Dim OutMail As Object
    Set outApp = CreateObject("Outlook.Application")
    Set oMail = outApp.CreateItem(0)
    Dim Doc As Object

    oMail.Display
    Set Doc = outApp.ActiveInspector.WordEditor

    oMail.To = ""
    oMail.Subject = "test"

    ' first sentence
    Dim msg As String
    msg = "Plain Sentence"

    Doc.Range(0, 0) = msg

    ' second sentence comes after
    msg = "Bold and Highlight Yellow Sentence"
    Doc.Range(Len(Doc.Range), Len(Doc.Range)) = msg
    Doc.Range.Font.Bold = True
    Doc.Range.HighlightColorIndex = wdYellow

    ' paste image below it
    Dim imagerng As Range
    Set imagerng = Range(Cells(1, 1), Cells(5, 5))
    imagerng.CopyPicture Appearance:=xlScreen, Format:=xlBitmap

    Doc.Range(Len(Doc.Range), Len(Doc.Range)).Paste

End Sub

基本上我想要做的是创建和显示如下所示的电子邮件:

  

普通句子   大胆而突出的黄色句子(这句话粗体而且突出显示)
  (位图图像​​)
  {my signature}

但是,我从代码中得到的输出是

  普通句(粗体)
  (位图图像​​)和第二句{my signature}

我该如何修复我的代码?

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您尝试在Word对象模型中访问范围的方式。在一些谷歌搜索后,我已用段落引用替换了您的Doc.Range(Len(Doc.Range), Len(Doc.Range)).部分。见下文:

Sub CreateEmailAndSend()

    Dim outApp As Object
    Dim OutMail As Object
    Set outApp = CreateObject("Outlook.Application")
    Set oMail = outApp.CreateItem(0)
    Dim Doc As Object

    oMail.Display
    Set Doc = outApp.ActiveInspector.WordEditor

    oMail.To = ""
    oMail.Subject = "test"

    ' first sentence
    Dim msg As String
    msg = "Plain Sentence"

    Doc.Range(0, 0) = msg

    ' second sentence comes after
    msg = "Bold and Highlight Yellow Sentence"

    Doc.Paragraphs(1).Range.InsertParagraphAfter
    Doc.Paragraphs(2).Range = msg
    Doc.Paragraphs(2).Range.Font.Bold = True
    Doc.Paragraphs(2).Range.HighlightColorIndex = wdYellow


    ' paste image below it
    Dim imagerng As Range
    Set imagerng = Range(Cells(1, 1), Cells(5, 5))
    imagerng.CopyPicture Appearance:=xlScreen, Format:=xlBitmap

    Doc.Paragraphs(2).Range.InsertParagraphAfter
    Doc.Paragraphs(3).Range.InsertParagraphAfter
    Doc.Paragraphs(3).Range.Paste

End Sub

现在这对我有用。

相关问题