Function to Paste Excel Range on Outlook Mail Body (In text not image) Function Name - rngHTML()

Use the below function in your subroutine in the below mentioned way:

.HTMLBody = str & rngHTML(Sheet1.Range("a13:g17"))  & .HTMLBody

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Function rngHTML(rng As Range)

    Dim fso As Object, ts As Object, TempWB As Workbook

    Dim TempFile As String


    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    '' copy the range and create a new workbook to paste the data into

    rng.Copy

    Set TempWB = Workbooks.Add(1)

    With TempWB.Sheets(1)

        .Cells(1).PasteSpecial Paste:=8

        .Cells(1).PasteSpecial xlPasteValues, , False, False

        .Cells(1).PasteSpecial xlPasteFormats, , False, False

        .Cells(1).Select

        Application.CutCopyMode = False

        On Error Resume Next

        .DrawingObjects.Visible = True

        .DrawingObjects.Delete

        On Error GoTo 0

    End With


    '' publish the sheet to a htm file

    With TempWB.PublishObjects.Add( _

         SourceType:=xlSourceRange, _

         Filename:=TempFile, _

         Sheet:=TempWB.Sheets(1).Name, _

         Source:=TempWB.Sheets(1).UsedRange.Address, _

         HtmlType:=xlHtmlStatic)

        .Publish (True)

    End With


    '' read all data from the htm file into rngHTML

    Set fso = CreateObject("Scripting.FileSystemObject")

    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)

    rngHTML = ts.readall

    ts.Close

    rngHTML = Replace(rngHTML, "align=center x:publishsource=", _

                          "align=left x:publishsource=")


    TempWB.Close savechanges:=False

    '' delete the htm file we used in this function

    Kill TempFile


    Set ts = Nothing

    Set fso = Nothing

    Set TempWB = Nothing

End Function

Comments

Popular posts from this blog

Power Automate - Automatically fetch data from Power BI in to Excel and Send the copy of the Excel file via Email

Separate Text (Characters) & Numbers from Alpha Numeric String Using Formula and Macro (VBA)