【问题标题】:Paste Excel range as picture into email body将 Excel 范围作为图片粘贴到电子邮件正文中
【发布时间】:2019-08-02 00:04:44
【问题描述】:

我的目标是将范围作为图像粘贴到 Outlook 电子邮件中。我在 VBA 编辑器中打开了 MS Excel、Word 和 Outlook 15.0 的引用作为我网络上的最新版本。

我花了好几个小时查看以前回答过的类似问题。

我无法将图像保存为临时文件/使用 html 来引用附件作为解决方案,因为其他用户无权访问特定驱动器,如果他们在自己的机器上运行代码会临时保存该驱动器。

如果我删除电子邮件正文部分,图像会很好地粘贴,但是如果我将两段代码放在一起,则电子邮件正文会覆盖图像。但是,我确实需要将图像粘贴到电子邮件正文中。

Sub CreateEmail()

Dim OlApp As Object
Dim OlMail As Object
Dim ToRecipient As Variant
Dim CcRecipient As Variant
Dim PictureRange As Range
Dim OApp As Object, OMail As Object, signature As String

Set OlApp = CreateObject("Outlook.Application")
Set OlMail = OlApp.createitem(olmailitem)

ExtractName = ActiveWorkbook.Sheets("macros").Range("C11").Value

ToRecipient = ActiveWorkbook.Sheets("macros").Range("K11")
OlMail.Recipients.Add ToRecipient

CC_Check = ActiveWorkbook.Sheets("macros").Range("k10")
If CC_Check = "" Then GoTo Skip_CC

CcRecipient = ActiveWorkbook.Sheets("macros").Range("K10")

OlMail.Recipients.Add CcRecipient

OlMail.Subject = ExtractName
signature = OlMailbody
With OlMail
Set PictureRange = ActiveWorkbook.Sheets("DCTVV").Range("A2:D13")
PictureRange.Copy
OlMail.Display

'This section pastes the image             

Dim wordDoc As Word.Document
Set wordDoc = OlMail.GetInspector.WordEditor
wordDoc.Range.PasteAndFormat wdChartPicture

'This section is the email body it needs inserting into

OlMail.body = "Text here," & vbNewLine & vbNewLine & _
        "Today's report is attached." & vbNewLine & _
        "IMAGE NEEDS TO BE PASTED HERE" _
      & vbNewLine & vbNewLine & "More text here" _
      & vbNewLine & vbNewLine & "Kind regards,"
.signature

End With
Set OMail = Nothing
Set OApp = Nothing
OlMail.Attachments.Add ("filepath &attachment1")
OlMail.Attachments.Add ("filepath &attachment2")
'OlMail.Attachments.Add ("filepath &attachment3")

OlMail.Display 

End Sub

【问题讨论】:

  • 查看rangeToHTML。这可能对你更有效
  • 由于文件夹的原因,您正在跳过文件的临时保存...我的工作是将图像保存在ThisWorkbook.Path 中,建立电子邮件后,删除所有文件。 .. 他们将始终可以访问他们使用文件的路径。
  • 我相信您也可以使用CopyPicture 吗?
  • @ScottHoltzman 这种方法会保持条件格式吗?如果没有,那么我将不得不遗憾地粘贴为图像
  • @Nathan_Sav 我复制范围没有问题,只需将其粘贴到电子邮件正文中的确切位置

标签: excel vba outlook


【解决方案1】:

如果您的代码在迁移到 Office 365 后突然停止工作或由于任何其他原因,请参阅下面的代码。添加了注释以便于理解和实施。

如果您拥有管理权限,请尝试以下链接中的注册表更改: https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

但是,作为开发人员,我建议使用与所有 Excel 版本相当兼容的代码,而不是进行系统更改,因为每个最终用户的计算机也需要进行系统更改。

由于下面的 VBA 代码使用“后期绑定”,它还兼容所有以前和当前版本的 MS Office 即。 Excel 2003、Excel 2007、Excel 2010、Excel 2013、Excel 2016、Office 365


Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)


    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String
    
    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"
    
    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)
  
    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject
        
        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)
        
        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:" & strTempFileName & ".png' style='border:0'>"

        
        .Display
        
    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String
    
    wksName = rngToPicture.Parent.Name
    
    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0
    
    'Copy the range as picture
    rngToPicture.CopyPicture
    
    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub

【讨论】:

    【解决方案2】:

    据我了解,图片可以很好地粘贴到电子邮件的正文中,对吧?

    在这种情况下,您可能只需要像这样添加.HTMLBody

    olMail.HTMLBody = "Text here," & vbNewLine & vbNewLine & _
            "Today's report is attached." & vbNewLine & _
            .HTMLBody & _
            vbNewLine & vbNewLine & "More text here" & _
            vbNewLine & vbNewLine & "Kind regards,"
    

    【讨论】:

    • 嗨丹尼尔,是的,如果我省略电子邮件正文部分,图片粘贴得很好。我想做的是将粘贴的图像包含在 OlMail.body 中,而不必出于上述原因引用附件
    • 是的,语法错误/编译错误我能否请您修改我上面的代码以包含您的建议,以防我遗漏了什么?
    • 对不起,我盲目地复制了您的代码并建议更正,但没有检查它,我现在已经编辑了它 - 如果它有效,请告诉我
    • 非常感谢,我应该能够使用 html 来修改这个来格式化电子邮件。我不确定代码的第 3 行如何将图片粘贴到该特定位置,但无论如何再次感谢!
    • 不用担心,基本上你正在创建一个新的身体,但它的一部分是旧的身体(第三行),这是你之前粘贴的图片。玩转 .body 和 .htmlbody 属性,看看哪种更适合你。如果对您有用,请不要忘记将其标记为正确答案:) ta
    【解决方案3】:

    这是我在工作中发送电子邮件时使用的代码示例:

        Call CrearImagen
        ReDim myFileList(0 To Contador - 1)
        For i = 0 To Contador - 1
            myFileList(i) = wb.Path & "\" & Servicio & i & ".jpg"
            ImagenesBody = ImagenesBody & "<img src='cid:" & Servicio & i & ".jpg'>"
        Next i
    
        With OutMail
            .SentOnBehalfOfName = "ifyouwanttosendonbehalf"
            .Display
            .To = Para
            .CC = CC
            .BCC = ""
            .Subject = Asunto
            For i = 0 To UBound(myFileList)
                .Attachments.Add myFileList(i)
            Next i
            Dim Espacios As String
    
            Espacios = "<br>"
            For i = 0 To x
                Espacios = Espacios + "<br>"
            Next
    
            .HTMLBody = Saludo & "<br><br>" & strbody & "<br><br><br>" _
                & ImagenesBody _ 'here are the images
                & Espacios _ 'more text
                & .HTMLBody
            .Display
        End With
        On Error GoTo 0
    
    'Reformateamos el tamaño de las imagénes y su posición relativa al texto
    
        Dim oL As Outlook.Application
    
        Set oL = GetObject("", "Outlook.application")
        Const wdInlineShapePicture = 3
        Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object
        Set olkMsg = oL.Application.ActiveInspector.CurrentItem
        Set wrdDoc = olkMsg.GetInspector.WordEditor
        For Each wrdShp In wrdDoc.InlineShapes
            If wrdShp.Type = wdInlineShapePicture Then
                wrdShp.ScaleHeight = 100
                wrdShp.ScaleWidth = 100
            End If
            If wrdShp.AlternativeText Like "cid:Imagen*.jpg" Then wrdShp.ConvertToShape
        Next
    
    'Limpiamos los objetos
        For i = 0 To UBound(myFileList)
            Kill myFileList(i)
        Next i
        Set olkMsg = Nothing
        Set wrdDoc = Nothing
        Set wrdShp = Nothing
        Set OutMail = Nothing
        Set OutApp = Nothing
    

    现在,如果您已经可以创建图像,只需将它们保存在工作簿路径中,您就可以像这样附加它们。在附加图片时,我建议你文件的名称不包含空格,这很难找到,直到弄清楚,html 不喜欢它们有空格。

    【讨论】:

    • 嗨 Damian,正如我在原始消息中所说,由于文件路径限制,我无法使用此方法,其他用户将使用工作簿并且无权访问临时文件夹等。非常感谢跨度>
    • 他们是否使用电子邮件中的文件?来自他们无法写入的驱动器?
    • 您也可以使用通用临时驱动器来保存文件,因此它适用于所有用户计算机:environ("temp") &amp; "file.jpeg"
    • @Scott Holtzman 你忘了最后的“\”,它的意思是 environ("temp") & "\file.jpeg"
    • @Damian 我愿意试一试您的建议,能否请您修改我上面粘贴的代码以包含您的建议?我在实施它时遇到了麻烦,而且我的西班牙语也不是很好哈哈!
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2014-07-24
    • 1970-01-01
    • 2012-12-04
    相关资源
    最近更新 更多