Comparing the Dates and Sending an Email - excel

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

Related

Only one message with HTML code in a loop is sent

Following Ron de Bruin's indications here, I created a VBA script to send each of my students an e-mail with their qualification. Each message contains text and a range with two rows and is composed in HTML format.
The routine seems to work using the .Display method of the Outmail object created in the script.
When I change .Display to .Send only the first message in the list is sent and, during tests, several times I had to close Outlook from the Task Manager because it is hung without closing. If I do this and run the script again, then the messages are sent and each receiver receives the message twice.
Here's a sample of the code:
Option Explicit
Sub GetLblAddress()
Dim wb As Workbook
Dim ws As Worksheet
Dim oLblRg As Range
On Error Resume Next
' Range C2:I2 contains labels of points earned in each exercise
Set oLblRg = Application.InputBox(Prompt:="Select labels in worksheet", _
Title:="SEND NOTES", _
Default:="C2:I2", _
Type:=8)
'Missing error trap yet!
Set ws = oLblRg.Parent
Set wb = ws.Parent
SendNotes wb, ws, oLblRg.Address
End Sub
Sub SendNotes(wb As Workbook, ws As Worksheet, sIniAd As String)
Const sSIGN As String = "<br><br>" & "Saludos" & "<br><br>" & "myname here"
Dim wsList As Worksheet
Dim rng As Range
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.mailitem
Dim OutAccount As Outlook.Account
Dim mailAd As String
Dim rw, lstRw, nCol, numSend As Long
Dim sAd, s As String
Dim sTo, sSubj, sBody As String
Dim bSend As Boolean
On Error GoTo CleanUp:
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
'worksheet "Listado" contains e-mail addresses in column H
Set wsList = wb.Worksheets("Listado")
With ws
If .Range(sIniAd).Rows.Count <> 1 Or Left(.Range(sIniAd)(1, 1), 1) <> "P" Then
Err.Raise 1
End If
End With
lstRw = ws.Cells(Rows.Count, 1).End(xlUp).Row
'Here begins loop that runs through the range of qualifications
'and send the corresponding row to each student present in the exam
numSend = 0
Application.StatusBar = "Creando instancia de Outlook." 'Just to keep me informed
Set OutApp = CreateObject("Outlook.Application")
Set OutAccount = OutApp.Session.Accounts("MyAddress#gmail.com")
For rw = 3 To lstRw
bSend = False
With ws
nCol = .Range(sIniAd).Columns.Count + 2
sAd = sIniAd & "," & .Cells(rw, 3).Address & ":" & .Cells(rw, nCol).Address
'Range rng contains two rows: labels and marks
Set rng = .Range(sAd)
sTo = wsList.Cells(rw, 8) 'Mail address of the student
sSubj = "Notas del Examen"
sBody = "Hola." & "<br><br>" & "Tu calificación en el examen es:" & "<br><br>"
'Set boolean variable bSend to know wether send a message
bSend = IsNumeric(.Cells(rw, 3)) And UCase(.Cells(rw, 10).Value) = "NO" And sTo <> vbNullString
End With
'Here's the "meat"
If bSend Then
Set OutMail = OutApp.CreateItem(olmailitem)
With OutMail
.To = sTo
.Subject = sSubj
.HTMLBody = sBody & RangetoHTML(rng) & sSIGN
.SendUsingAccount = OutAccount
.Display 'or use .SEND
End With
numSend = numSend + 1
'Sets the "Send" state to Yes
ws.Cells(rw, 10) = "SI"
End If
'Report advance of script into the status bar
Application.StatusBar = "Procesando: " & rw - 2 & "/" & lstRw - 2 & " (" & Format((rw - 2) / (lstRw - 2), "0%") & ")."
Next rw
CleanUp:
Application.StatusBar = False
Application.CutCopyMode = False
Set OutMail = Nothing
Set OutApp = Nothing
Set ws = Nothing
Set wsList = Nothing
If Err.Number <> 0 Then
If Err.Number = 1 Then
MsgBox "Debe seleccionar sólo la fila de ETIQUETAS", vbExclamation, "SEND NOTES"
ElseIf rng Is Nothing Then
MsgBox "No hay un rango seleccionado o la hoja está protegida," & _
vbNewLine & "corregir e intentar nuevamente.", vbExclamation, "SEND NOTES"
Else
MsgBox Err.Description, vbExclamation, "SEND NOTES"
End If
ElseIf numSend = 0 Then
MsgBox "No se han enviado mensajes.", vbInformation, "SEND NOTES"
ElseIf numSend = 1 Then
MsgBox "Se ha enviado 1 mensaje.", vbInformation, "SEND NOTES"
Else
MsgBox "Se han enviado " & numSend & " mensajes.", vbInformation, "SEND NOTES"
End If
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Function RangetoHTML(rng As Range)
'Extracted from http://www.rondebruin.nl/win/s1/outlook/bmail2.htm
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).CurrentRegion.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
Alternative question: Is it possible to include HTML code in a message without using Outlook (something like what is suggested here)?

How to past data from array into part of html body

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

Transfer Hyperlinks in Excel Range to Outlook Email

I am trying to create an email from excel ranges (rng 1 through 6) that have hyperlinks for each cell in Columns A and D. Here is an example of the code that creates the hyperlinks for these ranges. That all works just fine.
ActiveSheet.Hyperlinks.Add Anchor:=ActiveWorkbook.Sheets("Overdue").Range("A" & D2), _
Address:="some address" & ActiveWorkbook.Sheets("Overdue").Range("A" & D2).Value
ActiveSheet.Hyperlinks.Add Anchor:=ActiveWorkbook.Sheets("Overdue").Range("D" & D2), _
Address:="some other address" & ActiveWorkbook.Sheets("Overdue").Range("A" & D2).Value
I then have the below code that creates an email from the excel ranges (rng1 through 6). When the email is created the hyperlinks do not transfer to Outlook. The text is underlined as if there is a hyperlink but it is not clickable.
Sub Mail_Body()
Dim rng1 As Range
Dim OutApp As Object
Dim OutMail As Object
Dim wb2 As Workbook
Dim MyDate, Weeknr, MyFileName, MyTime, MyMonth
Dim Mail1 As String
Dim Mail2 As String
Dim Subject As String
Dim Warr As String
Dim rng2 As Range
Dim rng3 As Range
Dim rng4 As Range
Dim rng5 As Range
Dim rng6 As Range
Dim Subject_email As String
Application.ScreenUpdating = False
Application.EnableEvents = False
nPath = Environ("temp") & "\" & ThisWorkbook.Sheets("Lists").Range("AA1").Value
Set wb2 = Workbooks.Open(nPath)
D2 = Sheets("Critical").Range("A1").Offset(Sheets("Critical").Rows.Count - 1, 0).End(xlUp).Row
D3 = Sheets("High").Range("A1").Offset(Sheets("High").Rows.Count - 1, 0).End(xlUp).Row
D4 = Sheets("Low").Range("A1").Offset(Sheets("Low").Rows.Count - 1, 0).End(xlUp).Row
D5 = Sheets("Other").Range("A1").Offset(Sheets("Other").Rows.Count - 1, 0).End(xlUp).Row
D6 = Sheets("Overdue").Range("A1").Offset(Sheets("Overdue").Rows.Count - 1, 0).End(xlUp).Row
Set rng = Nothing
Set rng1 = Nothing
Set rng2 = Nothing
Set rng3 = Nothing
Set rng4 = Nothing
Set rng5 = Nothing
Set rng6 = Nothing
Set rng2 = Sheets("Critical").Range("A1:J" & D2).SpecialCells(xlCellTypeVisible)
Set rng3 = Sheets("High").Range("A1:J" & D3).SpecialCells(xlCellTypeVisible)
Set rng4 = Sheets("Low").Range("A1:J" & D4).SpecialCells(xlCellTypeVisible)
Set rng5 = Sheets("Other").Range("A1:J" & D5).SpecialCells(xlCellTypeVisible)
Set rng6 = Sheets("Overdue").Range("A1:L" & D6).SpecialCells(xlCellTypeVisible)
Set OutMail = Nothing
Set OutApp = Nothing
On Error Resume Next
Set OutApp = GetObject(, "Outlook.Application")
If OutApp Is Nothing Then Set OutApp = CreateObject("Outlook.Application")
On Error GoTo 0
'MsgBox OutApp
Set OutMail = OutApp.CreateItem(0)
Dim Session As Object
Set Session = OutApp.GetNamespace("MAPI")
Session.Logon
Create email
With OutMail
.To = Mail1
.CC = Mail2
.BCC = ""
.Subject = Subject_email
.HTMLBody = "Overview:" & "<br>" & RangetoHTML(rng1) _
& "<br>" & "<u>Critical</u>" & "<br>" & RangetoHTML(rng2) & "<br>" & "<u>High</u>" _
& "<br>" & RangetoHTML(rng3) & "<br>" & "<u>Low</u>" & "<br>" & RangetoHTML(rng4) _
& "<br>" & "<u>Other</u>" & "<br>" & RangetoHTML(rng5) _
& "<br>" & "<u>Overdue</u>" & "<br>" & RangetoHTML(rng6)
.Attachments.Add nPath '.FullName
.Recipients.ResolveAll
.Display '.Send
End With
I'm unable to share the output of this code, but what happens, as explained above, is the hyperlinks from the Excel sheet do not transfer to the Outlook email. They are blue and underlined but there is no hyperlink.
How do I carry over the active hyperlinks from excel to outlook? I've been unable to find a pre-existing solution that fits my specific needs.
I found a solution to the issue: https://www.mrexcel.com/forum/excel-questions/560111-retain-hyperlinks-after-rangetohtml-paste-outlook.html
In the RangetoHTML function, change the .pastevalues to .pasteall and the hyperlinks will be copied over.
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2010
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
Dim r As Long
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 xlPasteAll, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).PasteSpecial xlPasteRowHeights
.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

Sending Excel table in MailBody

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

Reply the email in PST outlook that have same value in Excel file [ Same Value is Service Tag ]

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

Resources