0

I am working on a Code which can get the range/selection in the middle of the email body. The below code works a bit fine for me it does not captures the desired range in the middle of the email body. This will save my time to work manually.

Sub Selection_email()

Dim bStarted As Boolean
Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim olMailItm As Object: Set olMailItm = olApp.CreateItem(0)
Dim rngTo As Range
Dim rngSubject As Range
Set oOutlookApp = GetObject(, "Outlook.Application")

If Err <> 0 Then

Set oOutlookApp = CreateObject("Outlook.Application")
bStarted = True

End If

Set oItem = oOutlookApp.CreateItem(olMailItem)
With Active Sheet

Set rngTo = .Rng("E3")
Last = ActiveSheet.Cells(2, 4).Value

End With

With oItem

.SentOnBehalfOfName = ""
.To = rngTo.Value
.Cc = ""
.Subject = "" & Last & ""
.body = "Hello," & vbNewLine & vbNewLine & _
            "Welcome to My World"& vbNewLine & vbNewLine & _
            **HERE I NEED THE CODE TO PASTE THE RANGE FROM THE EXCEL FILE IT SHOULD BE FROM "A1:D6"**
           "Thank you for your cooperation."
.Display.
If bStarted Then
oOutlookApp.Quit

End If

Set oOutlookApp = Nothing

End Sub
Community
  • 1
  • 1
Changer
  • 11
  • 1
  • 5

2 Answers2

1
Option Explicit

Sub Selection_email()
    Dim bStarted As Boolean
    Dim olApp As Object
    Dim oItem As Outlook.MailItem
    Dim olMailItm As Object
    Dim rngTo As Range
    Dim rngSubject As Range
    Dim Last As Variant
    Dim htmlString As String
    Dim beginBody, endBody As String
    Dim oOutlookApp As Outlook.Application

    Set olApp = CreateObject("Outlook.Application")
    Set olMailItm = olApp.CreateItem(0)
    Set oOutlookApp = GetObject(, "Outlook.Application")

    If Err <> 0 Then
        Set oOutlookApp = CreateObject("Outlook.Application")
        bStarted = True
    End If

    Set oItem = oOutlookApp.CreateItem(olMailItem)
    With ActiveSheet
        Set rngTo = .Range("E3")
        Last = ActiveSheet.Cells(2, 4).Value
    End With

    'create the HTML table first --
    '  this builds a string with proper HTML header info
    htmlString = RangetoHTML(ActiveSheet.Range("A1:D6"))
    'now add the email greeting to the body information
    beginBody = Left(htmlString, InStr(1, htmlString, "<body>", vbTextCompare) + 6)
    endBody = Right(htmlString, Len(htmlString) - InStr(1, htmlString, "<body>", vbTextCompare) + 5)
    htmlString = beginBody & _
                    "Hello,<br><br>Welcome to My World<br><br>" & _
                    endBody
    'now find the end of the table and add the signoff message
    beginBody = Left(htmlString, InStr(1, htmlString, "</div>", vbTextCompare) + 6)
    endBody = Right(htmlString, Len(htmlString) - InStr(1, htmlString, "</div>", vbTextCompare) + 5)
    htmlString = beginBody & _
                    "<br><br>Thank you for your cooperation." & _
                    endBody

    With oItem
        .SentOnBehalfOfName = ""
        .To = rngTo.Value
        .CC = ""
        .Subject = "" & Last & ""
        .HTMLBody = htmlString
        .Display
    End With

    If bStarted Then
        oOutlookApp.Quit
    End If

    Set oOutlookApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

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

    'Copy the range and create a new workbook to past the data in
    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 RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    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
PeterT
  • 8,232
  • 1
  • 17
  • 38
  • @ Peter: Not working can you Merge in the code for me or say can we have a code that it selects the range specified and then paste it in between the email body. – Changer Apr 02 '15 at 20:41
  • I believe I've misunderstood what you're trying to do (because I scanned the question too quickly). Perhaps this will help: [Ron de Bruin - Mail Range/Selection in the body of the mail](http://www.rondebruin.nl/win/s1/outlook/bmail2.htm) ? – PeterT Apr 02 '15 at 21:10
  • I Tried this perhaps this is of no use because i have multiple sheets and i just want to you that range in the middle of the email body. – Changer Apr 02 '15 at 21:37
  • So you want to create an HTML table with 6 rows and 4 columns in your email body showing the data from a specific worksheet with data from cells A1:D6? Then perhaps insert multiple HTML 6x4 tables with data from multiple sheets, each showing data from the range A1:D6? – PeterT Apr 03 '15 at 00:29
  • I would like to reiterate once again. I have sheet in which i there are 250 records a particular Location as common i will split those locations in multiple sheets. Now what want i want is the code what i have written above is correct but when i write the .body code i want the range A1:D6 in the middle of the email body. – Changer Apr 03 '15 at 12:53
  • @Sobigen was very close, and the link he provided to the other thread explains the situation. I modified my code above using your original code plus Ron de Bruin's `RangeToHTML` function. This works for me. – PeterT Apr 03 '15 at 14:01
  • I removed two lines from the code i.e. Dim oItem As Outlook.MailItem and Dim oOutlookApp As Outlook.Application and it worked fine. However, i wanted Thanks for your corporation below the range but the range is coming after Thanks for your corporation. – Changer Apr 03 '15 at 14:46
  • All you have to do is look at the temp file with the HTML and determine where to insert whatever text you want at whatever point in the message. The code above was modified to show how to put your "Thanks..." sign-off after the table. – PeterT Apr 03 '15 at 15:01
  • This is Amazing and exactly what i was looking for. You guys are wonderful and rocking. Cheers....!!!! – Changer Apr 03 '15 at 15:18
0

I'm assuming "A1:D6" is one merged ranged. You only want the top left cell in that case. If I've made an incorrect assumption let me know. .body = "Hello," & vbNewLine & vbNewLine & _ "Welcome to My World"& vbNewLine & vbNewLine & _ Activesheet.range("A1").value & _ "Thank you for your cooperation."Replacing Activesheet with something more specific would also be a good idea but depends on your worksheets.

Edit

Using the RangeToHTML function found here: Paste specific excel range in outlook
Then change

 .body = "Hello," & vbNewLine & vbNewLine & _
            "Welcome to My World"& vbNewLine & vbNewLine & _
            **HERE I NEED THE CODE TO PASTE THE RANGE FROM THE EXCEL FILE IT SHOULD BE FROM "A1:D6"**
           "Thank you for your cooperation."

to

.HTMLBody = "Hello," & vbNewLine & vbNewLine & _
            "Welcome to My World"& vbNewLine & vbNewLine & _
            RangeToHTML(activesheet.range("A1:D6")) & _
           "Thank you for your cooperation."
Community
  • 1
  • 1
Sobigen
  • 2,038
  • 15
  • 23
  • "A1:D6" is not a Merged Cell. This works fine when only Range("A1") is coded. I want "A1:D6" range to be there in the middle of the email body. – Changer Apr 02 '15 at 19:44
  • Its giving me an error as Compile error: Sub or Function not Defined and it is highlighted on RangeToHTML. – Changer Apr 02 '15 at 20:59
  • You have to copy the method from the link. It's a method created by another user, not one that part of VBA already. – Sobigen Apr 03 '15 at 02:00
  • I am not sure how to work on this as i lack a lot of knowledge on this. – Changer Apr 03 '15 at 13:18