I am using this code to send an e-mail via VBA, but I need to send a table as a Body.
This code sends only a one cell not a range.
How can I paste Range("B5:D10") as a table in mail body?
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = Range("B1").Value
.Cc = Range("B2").Value
.Bcc = Range("B3").Value
.Subject = Range("B4").Value
.Body = Range("B5").Value
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
You can achieve that by setting HTMLBody instead of Body. But then, to have control over formatting of a message, you have to have basic konwledge of HTML.
The idea behind it is as follows: you have to put range content together with HTML tags like this:
Dim rng As Range, cell As Range, HtmlContent As String, i As Long, j As Long
Set rng = Range("B5:D10")
HtmlContent = "<table>"
For i = 5 To rng.Rows.Count + 4
HtmlContent = HtmlContent & "<tr>"
For j = 2 To rng.Columns.Count + 2
HtmlContent = HtmlContent & "<td>" & Cells(i, j).Value & "</td>"
Next
HtmlContent = HtmlContent & "</tr>"
Next
HtmlContent = HtmlContent & "</table>"
Then, to put this table in a message:
With OutMail
'...
.HTMLBody = HtmlContent
'...
End With
You can try like this.
Sub test()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
Set rng = Selection.SpecialCells(xlCellTypeVisible)
Set rng = Sheets("Sheet1").Range("B5:D10").SpecialCells(xlCellTypeVisible)
On Error Resume Next
With OutMail
.To = Range("B1").Value
.Cc = Range("B2").Value
.Bcc = Range("B3").Value
.Subject = Range("B4").Value
.HTMLBody = RangetoHTML(rng)
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
End Sub
Function RangetoHTML(rng As Range)
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"
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
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
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=")
TempWB.Close SaveChanges:=False
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
You can't.
Thant body argument accept only Strings.
And there's another problem: formatting.
If I remember well I was in you situation and use something like this to produce html file from range.
Then I used TStream to take the ".html" file and put the result in the body.
Wrapping all this is in a pseudo:
Public Sub Email()
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Dim FSObj As Scripting.FileSystemObject
Dim TStream As Scripting.TextStream
Dim rngeSend As Range
Dim strHTMLBody As String
'Select the range to be sent
Set rngeSend = Application.Range("B1:G35")
If rngeSend Is Nothing Then Exit Sub 'User pressed Cancel
On Error GoTo 0
'Now create the HTML file
ActiveWorkbook.PublishObjects.Add(xlSourceRange, "C:\sales\tempsht.htm", rngeSend.Parent.Name, rngeSend.Address, xlHtmlStatic).Publish True
'Create an instance of Outlook (or use existing instance if it already exists
Set olApp = CreateObject("Outlook.Application")
'Create a mail item
Set olMail = olApp.CreateItem(olMailItem)
'Open the HTML file using the FilesystemObject into a TextStream object
Set FSObj = New Scripting.FileSystemObject
Set TStream = FSObj.OpenTextFile("C:\sales\tempsht.htm", ForReading)
'Now set the HTMLBody property of the message to the text contained in the TextStream object
strHTMLBody = TStream.ReadAll
olMail.HTMLBody = strHTMLBody
olMail.To = "anybody#anywhere.com"
olMail.Subject = "Email Subject"
olMail.Send
Hope it helps!
The answer from saransh seems to be based on this solution by Ron de Bruin.
However, it has a flaw where cells that have text hidden by other cells will result in that text being cut off in the result.
This is because the html renders this text with style display:none.
A simple solution it to add a line when reading the html file.
After this line:
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
add:
RangetoHTML = Replace(RangetoHTML, "display:none", "")
This will result in the hidden text be displayed and the table to autosize the columns.
You can use this function below so that it return a string of html:
extracttablehtml(thisworkbook.worksheets("whatever"), range("A1:B5"))
Afterwards, you do:
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "anymail"
.Cc = ""
.Bcc = ""
.Subject = ""
.HTMLBody = extracttablehtml(thisworkbook.worksheets("whatever"), Range("A1:B5")) '<<<< Here it is
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
public function:
Public Function extracttablehtml(ws As Worksheet, rng As Range) As String
Dim HtmlContent As String, i As Long, j As Long
On Error GoTo 0
HtmlContent = "<table>"
For i = 1 To rng.Rows.Count
HtmlContent = HtmlContent & "<tr>"
For j = 1 To rng.Columns.Count
HtmlContent = HtmlContent & "<td>" & ws.Cells(i, j).Value & "</td>"
Next
HtmlContent = HtmlContent & "</tr>"
Next
HtmlContent = HtmlContent & "</table>"
extracttablehtml = HtmlContent
Error_Handler_Exit:
On Error Resume Next
If Not rng Is Nothing Then Set OutMail = Nothing
Exit Function
Error_Handler:
If Alert = True Then
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: single_prop_write_mail_proposal" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
End If
Resume Error_Handler_Exit
End Function
Related
im trying to pass on element from array into to html body, so far i have:
Public example As String
then function that returns on element from array
Sub products()
Dim aArray() As String
For j = 2 To 2
If Cells(j, 1).Value <> "" Then
ReDim aArray(1 To 1) As String
For i = 1 To 10
If Cells(j, i).Value = "Yes" Then
aArray(UBound(aArray)) = Cells(1, i).Value
ReDim Preserve aArray(1 To UBound(aArray) + 1) As String
End If
Next i
example = Left(Join(aArray, " & "), Len(Join(aArray, " & ")) - 3) ''example is one of the product name
End If
Next j
Call mail
End Sub
and Ron Debruin email creator
Sub mail()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set rng = Selection.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
body_of_email = example
product_name_1 = "very, very, very long product1 info"
product_name_2 = "very, very, very long product2 info"
product_name_3 = "very, very, very long product3 info"
product_name_4 = "very, very, very long product4 info"
On Error Resume Next
With OutMail
.To = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng) & body_of_email
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
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
What should I change to make "body_of_email" returns one of the 'product info' into HTMLBody not the 'example' from array?
thanks for any help!
edit
when i changed this line
.HTMLBody = RangetoHTML(rng) & body_of_email
into this
Select Case wynik
Case Is = "product_name_1 "
.HTMLBody = RangetoHTML(rng) & product_name_1
Case Is = "product_name_2 "
.HTMLBody = RangetoHTML(rng) & product_name_2
Case Is = "product_name_3 "
.HTMLBody = RangetoHTML(rng) & product_name_3
Case Is = "product_name_4 "
.HTMLBody = RangetoHTML(rng) & product_name_4
End Select
it helped
I want to insert a table of data from Sheet1 of my Excel workbook and my default signature.
I tried using HTMLBody but it displays the signature either before the table is displayed or nothing at all.
I tried changing the positions of the .HTMLBody.
I have to to send a mail of the below format:
To:
CC:
BCC:
Subject:
Body: should contain "Hi Please find below the details"
Then the Excel table with the data of range ("A3:F3)
Then my signature (which is the default signature in Outlook or something which could be created)
and SEND.
The below is the code.
Sub esendtable()
Dim outlook As Object
Dim newEmail As Object
Dim xInspect As Object
Dim pageEditor As Object
Set outlook = CreateObject("Outlook.Application")
Set newEmail = outlook.CreateItem(0)
With newEmail
.To = "avc#123.com"
.CC = ""
.BCC = ""
.Subject = "Data - " & Date
.Body = "Please find below the data"
.Display
Set xInspect = newEmail.GetInspector
Set pageEditor = xInspect.WordEditor
Sheet1.Range("B3:F3").Copy
pageEditor.Application.Selection.Start = Len(.Body)
pageEditor.Application.Selection.End =
pageEditor.Application.Selection.Start
pageEditor.Application.Selection.PasteAndFormat (wdFormatPlainText)
.Display
'.Send
Set pageEditor = Nothing
Set xInspect = Nothing
End With
Set newEmail = Nothing
Set outlook = Nothing
End Sub
You can handle your email's body by
Outlook.CreateItem(olMailItem).GetInspector.WordEditor.Range
So following simple code snippet
preserves the standard signature for a new email
pastes the Excel range as range, picture or plain text
adds text before Excel range and/or between it and signature
With pageEditor.Range
.Collapse 1 ' wdCollapseStart
.InsertBefore "Hi Please find below the details" & vbCrLf
.Collapse 0 ' wdCollapseEnd
.InsertAfter "Text before signature" & vbCrLf
.Collapse 1 ' wdCollapseStart
Sheet1.Range("B3:F3").Copy
.Paste
'.PasteAndFormat 13 ' wdChartPicture
'.PasteAndFormat 22 ' wdFormatPlainText
End With
If you add a reference to "Microsoft Word x.x Object Library" (and "Microsoft Outlook x.x Object Library") for early binding, you can replace the numbers by the corresponding Word ENUM constants.
You can use my code as below
Set outlook = CreateObject("Outlook.Application")
Set newEmail = outlook.CreateItem(0)
With newEmail
.display
signature = newEmail.HTMLBody
sig = HtmlToText(signature)
.To = ""
.CC = ""
.Subject = "Test"
.HTMLBody = "Dear team," & "<br>" & "<br>" & "Please check and fix the issue below. Thank you!"
Set xInspect = newEmail.GetInspector
Set pageEditor = xInspect.WordEditor
wb.Sheets(1).Range("a1:h" & lr).SpecialCells(xlCellTypeVisible).Copy
pageEditor.Application.Selection.Start = Len(.body)
pageEditor.Application.Selection.End = pageEditor.Application.Selection.Start
pageEditor.Application.Selection.PasteAndFormat (wdformatplaintext)
.display
.HTMLBody = .HTMLBody & signature
Set pageEditor = Nothing
Set xInspect = Nothing
End With
This works for me
Sub esendtable()
Dim rng As Range
Dim Outlook As Object
Dim newEmail As Object
Dim SigString As String
Dim Signature As String
Dim xInspect As Object
Dim pageEditor As Object
Set rng = Nothing
On Error Resume Next
' Only send the visible cells in the selection.
Set rng = ActiveSheet.Range("A3:F3")
' You can also use a range with the following statement.
Set rng = Sheets("YourSheet").Range("A3:F3").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set Outlook = CreateObject("Outlook.Application")
Set newEmail = Outlook.CreateItem(0)
SigString = "C:\Users\chipz\AppData\Roaming\Microsoft\Signatures\chipz_1.htm" ' Change chipz in path and signature file name
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
On Error Resume Next
With newEmail
.To = "recipient#test.com"
.CC = ""
.BCC = ""
.Subject = "Data - " & Date
.BodyFormat = olFormatHTML
.HTMLBody = RangetoHTML(rng) & "" & Signature
.Display
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
'.Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set newEmail = Nothing
Set Outlook = Nothing
Set newEmail = Nothing
Set Outlook = Nothing
End Sub
Function RangetoHTML(rng As Range)
' 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
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
I have a table in Excel that I want to send to a distribution list in Outlook with the table in the email body.
Using MVP Ron de Bruin's examples and a few others on here I've got code that keeps some of the table formatting but doesn't copy the cells colour if it is a gradient (please use the images as reference).
Sub DisplayEmailButton_Click()
Mail_Selection_Range_Outlook_Body
End Sub
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set rng = Sheets("Sheet1").Range("C2:Q18").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "Team01"
.CC = ""
.BCC = ""
.Subject = "Daily Statistics"
.HTMLBody = "Please see attached daily statistics." & vbCrLf &
RangetoHTML(rng)
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
Dim TempFile As String, ddo As Long
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
' Temporary publish the rng range to a htm file
ddo = ActiveWorkbook.DisplayDrawingObjects
ActiveWorkbook.DisplayDrawingObjects = xlHide
With ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=ActiveSheet.Name, _
Source:=Union(rng, rng).Address, _
HtmlType:=xlHtmlStatic)
.Publish True
.Delete
End With
ActiveWorkbook.DisplayDrawingObjects = ddo
'Read all data from the htm file into RangetoHTML
With
CreateObject("Scripting.FileSystemObject").GetFile(TempFile)
.OpenAsTextStream(1, -2)
RangetoHTML = Replace(.ReadAll, "align=center x:publishsource=", "align=left
x:publishsource=")
.Close
End With
'Delete the htm file we used in this function
Kill TempFile
End Function
As Tim suggested I was expecting way too much from that procedure (Thank you, Tim, for the advice!) so I looked into a workaround. If the range is saved as a picture then it keeps all the formatting and the picture can then easily be attached to an email or displayed in the body of the email.
To save as a picture:
Dim Wb As ThisWorkbook
Dim Ws As Worksheet
Dim Ch As Chart
Set Rng = Ws.Range("A1:G18")
Set Ch = Charts.Add
Ch.Location xlLocationAsObject, "Sheet2"
Set Ch = ActiveChart
ActiveChart.Parent.Name = "StatsTemp"
ActiveSheet.ChartObjects("StatsTemp").Height = Rng.Height
ActiveSheet.ChartObjects("StatsTemp").Width = Rng.Width
Rng.CopyPicture xlScreen, xlBitmap
Ch.Paste
Ch.Export Environ("UserProfile") & "\Desktop" & "\" & Format("TempImage") & ".jpg"
Worksheets("Sheet2").ChartObjects("StatsTemp").Delete
Worksheets("Sheet1").Activate
The above code saves the range as an image "TempImage.JPG" to the users desktop by creating a new chart on sheet 2, pasting the range to the chart then saves the chart as an image and deletes the chart.
To attach the picture to an email in the email body:
Dim StrBody As String
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
StrBody = "Some text here." & "<br>"
On Error Resume Next
With OutMail
.to = "email address"
.CC = ""
.BCC = ""
.Subject = "Email Subject"
.HTMLBody = StrBody & "<img src = '" & Environ("userProfile") &
"\desktop\TempImage.jpg'>"
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
The above code creates an email using Microsoft Outlook which contains the saved image file in the email body and displays the email.
The image can be deleted after using:
Kill Environ("UserProfile") & "\Desktop" & "\TempImage.jpg"
Hopefully, this will be of some use to someone!
Credit to Ron de Bruin Microsoft Office MVP for his WinTips!
I want to create automail that will reply the email in Outlook where located in PST file that have same subject in Excel.
Below is my excel file. I want to search email with same service tag #Column D
And reply with custom HTML body.
my problem now I cannot display my desired email and reply it.
Hope you all can help me.
Here is my code that I try.
Sub AutoMail()
'Find OOW_Request
Dim OOW As Workbook
Dim s As Workbook
For Each s In Workbooks
If Left(s.Name, 11) = "OOW Request" Then
Set OOW = Workbooks(s.Name)
End If
Next s
Dim rng As Range
Dim rngTilte As Range
Dim OutApp As Object
Dim OutMail As Object
Dim lRow As Integer
Dim i As Integer
Dim toDate As Date
Dim toList As String
Dim eSubject As String
Dim eBody As String
Dim eBodyLast As String
Dim olNs As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim olReply As Object ' Reply
Dim olRecip As Recipient ' Add Recipient
OOW.Sheets("OOW_REQUEST").Select
lRow = OOW.Sheets("OOW_REQUEST").Range("D" & Rows.Count).End(xlUp).Row
For i = 2 To lRow
If OOW.Sheets("OOW_REQUEST").Range("L" & i) = "" Then
Set rng = Nothing
Set rngTilte = Nothing
On Error Resume Next
Set rngTilte = OOW.Sheets("OOW_REQUEST").Range("D1:M1").SpecialCells(xlCellTypeVisible)
Set rng = OOW.Sheets("OOW_REQUEST").Range("D" & i & ":" & "M" & i). _
SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set olNs = OutApp.GetNamespace("MAPI")
olNs.AddStore ("C:\Users\Ruzaini_Subri\Documents\Outlook Files\OOW.pst")
Set myTasks = olNs.Session.Folders.Item(2).items
For Each olMail In myTasks
If (InStr(1, olMail.Subject, "Cells(i, 4)", vbTextCompare) > 0) Then
' toList = Cells(i, 8)
' eSubject = "yOOW part requestz|| Part: " & Cells(i, 5) & " || TAG: " & Cells(i, 4)
eBody = "<BODY style=font-size:10pt;font-family:Arial><p>Hi " & Cells(i, 8) & "</p>" & _
"Please advise if you can support this OOW request by replying this email." & "<br><br></BODY>"
eBodyLast = "<BODY style=font-size:9pt;font-family:Arial><br><br>" & "<p>Thank You.</p>" & _
"<strong>---------------------------------------------------------------------</strong><br>" & _
"<span style=""color: #333399;""><strong>Ruzaini Subri</strong></span></BODY>"
On Error Resume Next
Set olReply = olMail.ReplyAll
Set olRecip = olReply.Recipients.Add("& Cells(i, 8) &") ' Recipient Address
olRecip.Type = olTo
olReply.HTMLBody = eBody & RangetoHTML(rngTilte) & RangetoHTML(rng) & eBodyLast & vbCrLf & olReply.HTMLBody
olReply.Display
'olReply.Send
On Error GoTo 0
End If
Next olMail
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set olMail = Nothing
Set OutApp = Nothing
Cells(i, 12) = "TBU"
End If
Next i
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
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=")
RangetoHTML = Replace(RangetoHTML, "<!--[if !excel]> <![endif]-->", "")
'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
I solve this problem after search in internet
You can mapping Outlook folder ID in excel and refer it to find desired email.
Find Folder ID in Outlook
Sub Test()
Dim app As Outlook.Application
Dim nms As Outlook.Namespace
Dim fld As Outlook.Folder
Set app = GetObject(, "Outlook.Application")
Set nms = app.GetNamespace("MAPI")
Set fld = nms.PickFolder
Debug.Print "StoreID: " & fld.StoreID
Debug.Print "EntryID: " & fld.EntryID
Sheets("MACRO").Range("N10") = fld.StoreID
Sheets("MACRO").Range("N11") = fld.EntryID
Call MessageBoxTimer
End Sub
Use it in your code
Dim StoreID As Variant
Dim EntryID As Variant
StoreID = ws.Range("N1").Value
EntryID = ws.Range("N2").Value
For i = 2 To lRow
If OOW.Sheets("WORKING FILE").Range("W" & i) = "YES" And _
OOW.Sheets("WORKING FILE").Range("B" & i) = "Ruz" And _
OOW.Sheets("WORKING FILE").Range("Y" & i) = "" Then
Set rng = Nothing
Set rngTilte = Nothing
On Error Resume Next
Set rngTilte = OOW.Sheets("WORKING FILE").Range("D1:X1").SpecialCells(xlCellTypeVisible)
Set rng = OOW.Sheets("WORKING FILE").Range("D" & i & ":" & "X" & i). _
SpecialCells(xlCellTypeVisible)
On Error GoTo 0
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set olNs = OutApp.GetNamespace("MAPI")
Set Fldr = olNs.GetFolderFromID(EntryID, StoreID)
Set myTasks = Fldr.items
I want to send an automatic mail if two conditions are met
The user input date in Cell (17,2) is > than today's date in
Cell(22,2)'
When the value in Cell (B3) = "Operation_Support"
When the above two conditions are met then I want an automatic mail to shoot up.
Can this be done?
The code is given below..
Sub datesexcelvba()
Dim OutApp As Object
Dim OutMail As Object
Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long
Dim rng As Range
Dim StrBody As String
StrBody = "This is line " & "<br>" & _
"This is line " & "<br>" & _
"This is line " & "<br><br><br>"
mydate1 = Cells(17, 2).Value
mydate2 = mydate1
datetoday1 = Cells(22, 2).Value
datetoday2 = datetoday1
If mydate2 > datetoday2 & Range("B3").Value = "Operation_Support" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With mymail
.To = "x"
'& ";" & "x"
.CC = ""
.BCC = ""
.Subject = "Test Mail"
.HTMLBody = StrBody & RangetoHTML(rng)
.Attachments.Add ActiveWorkbook.FullName
' You can add other files by uncommenting the following line.
'.Attachments.Add ("C:\test.txt")
.Display
End With
End If
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
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
tested your code and encountered some minor issues. Assuming your Function
RangetoHTML()
works fine, you need to change the following to lines
If mydate2 > datetoday2 & Range("B3").Value = "Operation_Support" Then
...
With mymail
...
The changes are the following: Replace the '&' with 'And' and 'mymail' with the Object you set above (in your case it is OutMail).
So your Sub would be:
Sub datesexcelvba()
Dim OutApp As Object
Dim OutMail As Object
Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long
Dim rng As Range
Dim StrBody As String
StrBody = "This is line " & "<br>" & _
"This is line " & "<br>" & _
"This is line " & "<br><br><br>"
mydate1 = Cells(17, 2).Value
mydate2 = mydate1
datetoday1 = Cells(22, 2).Value
datetoday2 = datetoday1
If mydate2 > datetoday2 And Range("B3").Value = "Operation_Support" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "test#testing.com"
'& ";" & "x"
.CC = ""
.BCC = ""
.Subject = "Test Mail"
.HTMLBody = StrBody
'.Attachments.Add ActiveWorkbook.FullName
' You can add other files by uncommenting the following line.
'.Attachments.Add ("C:\test.txt")
.Display
End With
End If
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub