Astuce: Les autres langues sont Google-Traduction. Vous pouvez visiter le English version de ce lien.
Se connecter
x
or
x
x
S'enregistrer
x

or

Comment coller une plage de cellules dans le corps du message en tant qu'image dans Excel?

Si vous avez besoin de copier une plage de cellules et de le coller comme une image dans le corps du message lorsque vous envoyez un e-mail à partir d'Excel. Comment pourriez-vous faire face à cette tâche?

Collez une plage de cellules dans le corps de l'e-mail en tant qu'image avec le code VBA dans Excel


Collez une plage de cellules dans le corps de l'e-mail en tant qu'image avec le code VBA dans Excel


Peut-être qu'il n'y a pas d'autre bonne méthode pour vous de résoudre ce travail, un code VBA dans cet article peut vous aider. S'il vous plaît faites comme ceci:

1. Activer la feuille que vous souhaitez copier et coller les cellules en tant qu'image, maintenez la touche ALT + F11 clés pour ouvrir le Microsoft Visual Basic pour applications fenêtre.

2. Cliquez insérer > Moduleet collez le code suivant dans le Module Fenêtre.

Code VBA: coller une plage de cellules dans le corps de l'e-mail en tant qu'image:

Sub sendMail()
    Dim TempFilePath As String
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xHTMLBody As String
    Dim xRg As Range
    On Error Resume Next
    Set xRg = Application.InputBox("Please select the data range:", "KuTools for Excel", Selection.Address, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    With Application
        .Calculation = xlManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    Set xOutApp = CreateObject("outlook.application")
    Set xOutMail = xOutApp.CreateItem(olMailItem)
    Call createJpg(ActiveSheet.Name, xRg.Address, "DashboardFile")
    TempFilePath = Environ$("temp") & "\"
    xHTMLBody = "<span LANG=EN>" _
            & "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
            & "Hello, this is the data range that you want:<br> " _
            & "<br>" _
            & "<img src='cid:DashboardFile.jpg'>" _
            & "<br>Best Regards!</font></span>"
    With xOutMail
        .Subject = ""
        .HTMLBody = xHTMLBody
      .Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
        .To = " "
        .Cc = " "
        .Display
    End With
End Sub
Sub createJpg(SheetName As String, xRgAddrss As String, nameFile As String)
    Dim xRgPic As Range
    Dim xShape As Shape
    ThisWorkbook.Activate
    Worksheets(SheetName).Activate
    Set xRgPic = ThisWorkbook.Worksheets(SheetName).Range(xRgAddrss)
    xRgPic.CopyPicture
    With ThisWorkbook.Worksheets(SheetName).ChartObjects.Add(xRgPic.Left, xRgPic.Top, xRgPic.Width, xRgPic.Height)
        .Activate
        For Each xShape In ActiveSheet.Shapes
            xShape.Line.Visible = msoFalse
        Next
        .Chart.Paste
        .Chart.Export Environ$("temp") & "\" & nameFile & ".jpg", "JPG"
    End With
   Worksheets(SheetName).ChartObjects(Worksheets(SheetName).ChartObjects.Count).Delete
Set xRgPic = Nothing
End Sub

Note: Dans le code ci-dessus, vous pouvez modifier le contenu du corps et l'adresse e-mail à votre besoin.

3. Après avoir inséré le code, appuyez sur F5 Pour exécuter ce code, une boîte de dialogue apparaît pour vous rappeler de sélectionner la plage de données que vous souhaitez insérer dans le corps du message comme image, voir capture d'écran:

4. Puis clique OK bouton, et un Message fenêtre est affichée, la plage de données sélectionnée a été insérée dans le corps comme image, voir capture d'écran:

Note: Dans le Message fenêtre, vous pouvez également modifier le contenu du corps et les adresses e-mail dans les champs À et Cc selon vos besoins.

5. Enfin, cliquez Envoyer bouton pour envoyer cet email.


Note: Si vous devez coller plusieurs plages de différentes feuilles de calcul, le code VBA ci-dessous peut vous rendre service:

Tout d'abord, vous devez sélectionner les multiples plages que vous souhaitez insérer dans le corps de l'e-mail sous forme d'images, puis appliquez le code suivant:

Code VBA: collez plusieurs plages de cellules dans le corps du courrier électronique en tant qu’image:

Sub sendMail()
    Dim TempFilePath As String
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xHTMLBody As String
    Dim xRg As Range
    Dim xSheet As Worksheet
    Dim xAcSheet As Worksheet
    Dim xFileName As String
    Dim xSrc As String
    On Error Resume Next
    TempFilePath = Environ$("temp") & "\RangePic\"
    If Len(VBA.Dir(TempFilePath, vbDirectory)) = False Then
      VBA.MkDir TempFilePath
    End If
    Set xAcSheet = Application.ActiveSheet
    For Each xSheet In Application.Worksheets
        xSheet.Activate
        Set xRg = xSheet.Application.Selection
        If xRg.Cells.Count > 1 Then
            Call createJpg(xSheet.Name, xRg.Address, "DashboardFile" & VBA.Trim(VBA.Str(xSheet.Index)))
        End If
    Next
    xAcSheet.Activate
    With Application
        .Calculation = xlManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    Set xOutApp = CreateObject("outlook.application")
    Set xOutMail = xOutApp.CreateItem(olMailItem)
    xSrc = ""
    xFileName = Dir(TempFilePath & "*.*")
    Do While xFileName <> ""
        xSrc = xSrc + VBA.vbCrLf + "<img src='cid:" + xFileName + "'><br>"
        xFileName = Dir
        If xFileName = "" Then Exit Do
    Loop
    xHTMLBody = "<span LANG=EN>" _
                & "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
                & "Hello, this is the data range that you want:<br> " _
                & "<br>" _
                & xSrc _
                & "<br>Best Regards!</font></span>"
    With xOutMail
        .Subject = ""
        .HTMLBody = xHTMLBody
        xFileName = Dir(TempFilePath & "*.*")
        Do While xFileName <> ""
            .Attachments.Add TempFilePath & xFileName, olByValue
            xFileName = Dir
        If xFileName = "" Then Exit Do
        Loop
        .To = " "
        .Cc = " "
       .Display
    End With
    If VBA.Dir(TempFilePath & "*.*") <> "" Then
        VBA.Kill TempFilePath & "*.*"
    End If
End Sub
Sub createJpg(SheetName As String, xRgAddrss As String, nameFile As String)
    Dim xRgPic As Range
    ThisWorkbook.Activate
    Worksheets(SheetName).Activate
    Set xRgPic = ThisWorkbook.Worksheets(SheetName).Range(xRgAddrss)
    xRgPic.CopyPicture
    With ThisWorkbook.Worksheets(SheetName).ChartObjects.Add(xRgPic.Left, xRgPic.Top, xRgPic.Width, xRgPic.Height)
        .Activate
        .Chart.Paste
        .Chart.Export Environ$("temp") & "\RangePic\" & nameFile & ".jpg", "JPG"
    End With
    Worksheets(SheetName).ChartObjects(Worksheets(SheetName).ChartObjects.Count).Delete
Set xRgPic = Nothing
End Sub

Kutools for Excel résout la plupart de vos problèmes et augmente votre productivité de 80%

  • Réutilisation: Insérer rapidement formules complexes, graphiques et tout ce que vous avez utilisé auparavant; Crypter les cellules avec mot de passe Créer une liste de diffusion et envoyer des emails ...
  • Super Formula Bar (éditez facilement plusieurs lignes de texte et de formule); Disposition de lecture (facilement lire et éditer un grand nombre de cellules); Coller à la gamme filtrée...
  • Fusionner les cellules / rangées / colonnes sans perdre de données; Contenu des cellules divisées; Combiner les lignes / colonnes en double... Prévenir les cellules en double; Comparer les plages...
  • Sélectionnez Dupliquer ou Unique Des rangées; Sélectionnez les lignes vierges (toutes les cellules sont vides); Super Find et Fuzzy Find dans de nombreux cahiers d'exercices; Sélection aléatoire ...
  • Copie exacte Plusieurs cellules sans changer la référence de la formule; Créer automatiquement des références à plusieurs feuilles; Insérer des balles, Cases à cocher et plus ...
  • Extrait du texte, Ajouter du texte, Supprimer par position, Supprimer l'espace; Créer et imprimer des sous-totaux de pagination; Conversion entre contenu de cellules et commentaires...
  • Super filtre (enregistrer et appliquer des schémas de filtrage à d'autres feuilles); Tri avancé par mois / semaine / jour, fréquence et plus; Filtre spécial en gras, en italique ...
  • Combinaison de classeurs et de feuilles de calcul; Fusionner les tables en fonction des colonnes clés; Fractionner les données en plusieurs feuilles; Conversion par lots xls, xlsx et PDF...
  • Plus que de puissantes fonctionnalités 300. Prend en charge Office / Excel 2007-2019 et 365. Prend en charge toutes les langues. Déploiement facile dans votre entreprise ou organisation. Fonctionnalités complètes Essai gratuit du jour 30.
kte tab 201905

Office Tab apporte une interface à onglets à Office et simplifie grandement votre travail

  • Activer l'édition par onglets et la lecture dans Word, Excel, PowerPoint, Publisher, Access, Visio et Project.
  • Ouvrez et créez plusieurs documents dans de nouveaux onglets de la même fenêtre, plutôt que dans de nouvelles fenêtres.
  • Augmente votre productivité de 50% et réduit le nombre de clics de souris pour vous chaque jour!
fond officetab
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Windy · 1 months ago
    The code above works well on PC, while the picture can't be seen from mobile APP. It only showed "cid:DashboardFile.jpg". Is there any way to solve the issue?
  • To post as a guest, your comment is unpublished.
    Carlos · 2 months ago
    When I try to send a second email with the same rage but diffent info (is a pivot) is showing the 1st image on the second email. How do I delete the image after created or pasted on email?
  • To post as a guest, your comment is unpublished.
    Breaking bad · 2 months ago
    Join the club, even I am facing the same issue ,with borders around the image .
    .
    .
    Waiting for a fix.

    Fingers crossed !!!!
    • To post as a guest, your comment is unpublished.
      skyyang · 2 months ago
      Hello, Breaking,
      The code in this article has been updated, please try, hope it can help you!
      Thank you!
  • To post as a guest, your comment is unpublished.
    srilatha aithal · 2 months ago
    Hi
    This works great. But it has a border around the image. Is there a way to take this off.


    Thank you
    • To post as a guest, your comment is unpublished.
      skyyang · 2 months ago
      Hello, srilatha,
      The code in this article has been updated, please try, hope it can help you!
      Thank you!
      • To post as a guest, your comment is unpublished.
        srilatha aithal · 2 months ago
        This is awesome. Thanks a heap


        I got one last problem, my image appears a little blur and that happens only in one column .Any way to fix that.

        Thank you!!
  • To post as a guest, your comment is unpublished.
    Saisri · 2 months ago
    Hi,
    This works great, but has a border. Is there a way to remove the border
  • To post as a guest, your comment is unpublished.
    NoMadMax59 · 3 months ago
    Buongiorno,
    l'esecuzione del codice si ferma a xRgPic = ThisWorkbook.Worksheets(SheetName).Range(xRgAddrss) e torna alla sub sendMail senza creare l'immagine.

    Utilizzo Office 2010 e win7

    Come posso correggere?
  • To post as a guest, your comment is unpublished.
    Jackie · 4 months ago
    Hi Skyyang, can you let me have the code for sending two ranges from two sheets of the same work sheet, each range in a different image?
    • To post as a guest, your comment is unpublished.
      skyyang · 4 months ago
      Hello, Jackie,
      I have updated this article, you can use the code at the end of this article.
      Please try, hope it can help you!
      • To post as a guest, your comment is unpublished.
        Jackie · 4 months ago
        Sorry, never mind. It's my mistake on my part. One more question - how can I add a space in between the images?
        • To post as a guest, your comment is unpublished.
          skyyang · 4 months ago
          Hi, Jackie,
          To insert a blank row between the images, you just need to press Enter key at the end of the image in the email body.
      • To post as a guest, your comment is unpublished.
        Jackie · 4 months ago
        Hi skyyang, thank you very much. It works, for the most part. However, I have different ranges ("F1:N15") from sheet 1, and "H1:N15" from sheet 2. It seems always use the "F1:N15" range from both sheets. How can I make it change 2 different ranges?
  • To post as a guest, your comment is unpublished.
    Jose Goncales · 6 months ago
    This is amazing. One question: How can I send two ranges that are in two differents sheets of the same workbook, each range in a different image?
    • To post as a guest, your comment is unpublished.
      skyyang · 5 months ago
      Hi, Jose,
      The code is somewhat difficult, and it can not insert here, if you want to this code, you can give your email here, and i will send the code to your email.
      Thank you!
  • To post as a guest, your comment is unpublished.
    Jose Gonçalves · 6 months ago
    This is awesome!! Can you tell me how I can insert more than one image using this code? I need insert two interval of the same workbook, but they are in diferents sheets.
  • To post as a guest, your comment is unpublished.
    dadd · 6 months ago
    buongiorno… potreste dirmi cosa devo inserire al posto di quelle stringhe del codice in blu?
    • To post as a guest, your comment is unpublished.
      Jose Goncales · 6 months ago
      Queste linee blu indicano "text ", è probabilmente una formattazione dell'editor utilizzato per creare il códice.
  • To post as a guest, your comment is unpublished.
    Mohammad · 8 months ago
    Thanks dears,, Could you please tell me how to do this but without asking for range (predefined range)?
    • To post as a guest, your comment is unpublished.
      Carter · 7 months ago
      Did anyone ever reply to you?
      • To post as a guest, your comment is unpublished.
        Jay · 6 months ago
        Set xRg = Range("A1:J10")

        Just set xRg to whatever range you want/need it to be.
  • To post as a guest, your comment is unpublished.
    greg horton · 9 months ago
    This is awesome, I love it! Quick question. I see that it is adding a border to the image. Is there a way to generate without a border? Thanks in advance!
    • To post as a guest, your comment is unpublished.
      Ian Wildman · 8 months ago
      I'd love to know how to paste without generating a border as well. This code is awesome, super intuitive and straightforward. Thank you!
  • To post as a guest, your comment is unpublished.
    Piotrek · 1 years ago
    wyrzuca mi błąd w linijce "Set xOutMail = xOutApp.CreateItem(olMailItem)" olMailItem - nie zdefiniowana
    oraz ".Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue" olByValue - nie zdefiniowana