On Error Go To in a Loop - vba

I am trying to create a loop that will look through a list of customers, and if there is a report for that customer, email that customer the report.
What I need is an On Error statement that will allow customers without reports to be skipped and allow the script to continue onto the next customer right up until the end of the customer list.
The On Error statement I have currently, gets stuck after all customers have been cycled through, and continues looping in the On Error statement.
Any help would be greatly appreciated!!!
sub test()
a = 2
Check:
Do Until UniqueBuyer.Range("A" & a).Value = ""
On Error GoTo ErrHandler:
Sheets(UniqueBuyer.Range("A" & a).Value).Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
FolderLocation & FolderName & "\" & _
UniqueBuyer.Range("A" & a).Value & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=Flase, OpenAfterPublish:=False
PDFFile = FolderLocation & FolderName & "\" & _
UniqueBuyer.Range("A" & a).Value & ".pdf"
Set OutLookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutLookApp.createItem(0)
CombinedEmail = ""
'Clear variable - LK
On Error Resume Next
'Display email and specify To, Subject, etc
With OutlookMail
.Display
c = 4
Do Until UniqueBuyer.Cells(a, c).Value = ""
AdditionalEmail = UniqueBuyer.Cells(a, c)
CombinedEmail = CombinedEmail & ";" & AdditionalEmail
.to = CombinedEmail
c = c + 1
Loop
.cc = ""
.BCC = ""
.Subject = "Weekly Wooltrade Summary " & Left(Master.Range("X2"), 3)
.Body = ""
.Attachments.Add PDFFile
'.Send
End With
On Error GoTo 0
a = a + 1
Loop
Exit Sub
ErrHandler:
a = a + 1
GoTo Check
End Sub

the On Error GoTo way is hardly the one to go: you'd better check for any possible error and handle it
furthermore you'd also better instantiate one Outlook Application only for all needed emails
finally there were some typos (Flase -> False)
here's a possible (commented) refactoring of your code for what above:
Option Explicit
Sub test()
Dim UniqueBuyer As Worksheet, Master As Worksheet
Dim FolderLocation As String, FolderName As String, PDFFile As String
Dim OutLookApp As Object
Dim cell As Range
FolderLocation = "C:\Users\...\" '<--| change it to your actual folder location
FolderName = "Test" '<--| change it to your actual folder name
Set UniqueBuyer = Worksheets("UniqueBuyer") '<--| change "UniqueBuyer" to your actual Unique Buyer sheet name
Set Master = Worksheets("Master") '<--| change "Master" to your actual Master sheet name
Set OutLookApp = CreateObject("Outlook.Application") '<--| set one Outlook application outside the loop
With UniqueBuyer '<--| reference your "Unique Buyer" sheet
For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues) '<--| loop through its column A cells with constant (i.e. not from formulas) text content from row 2 down to last not empty one
PDFFile = FolderLocation & FolderName & "\" & cell.Value & ".pdf" '<--| build your PDF file name
With .Range(cell.Offset(, 3), cell.Offset(, 3).End(xlToRight)) '<--| reference current buyer cells from column 4 rightwards
If WorksheetFunction.CountA(.Cells) > 0 Then '<--| if any not-blank cells in referenced ones
If OKSheetAndExportToPDF(cell.Value, PDFFile) Then '<--| if successfully found current buyer sheet and exported it to PDF
'Display email and specify To, Subject, etc
With OutLookApp.createItem(0) '<--| create a new mail item and reference it
.Display
.to = GetCombinedEmails(.SpecialCells(xlCellTypeConstants, xlTextValues)) '<--| get emails string from currently referenced cells with some constant text value
.cc = ""
.BCC = ""
.Subject = "Weekly Wooltrade Summary " & Left(Master.Range("X2"), 3)
.Body = ""
.Attachments.Add PDFFile
'.Send
End With
End If
End If
End With
Next
End With
Set OutLookApp = Nothing
End Sub
Function GetCombinedEmails(rng As Range) As String
Dim cell As Range
With rng
If .Count = 1 Then
GetCombinedEmails = .Value
Else
GetCombinedEmails = Join(Application.Transpose(Application.Transpose(.Value)), ";") '<--| join all found consecutive email addresses in one string
End If
End With
End Function
Function OKSheetAndExportToPDF(shtName As String, PDFFile As String) As Boolean
On Error GoTo ExitFunction
With Worksheets(shtName)
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=PDFFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
OKSheetAndExportToPDF = True
End With
ExitFunction:
End Function

Related

Create loop to go down cell then repeat macro code

I currently have a code that Saves the excel sheet in a PDF based on infomation specific to the text in cell B2, and then attach the PDF into an email and email out to the specific user.
I am unsure how to add a macro to the current code to have the cell in B2 go down the data validation list inbetted and then repeat the macro to send the next person the email specific to them.
This is the current code that I have to save pdf and then email:
Sub AttachActiveSheetPDF()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object
Title = Range("A1")
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = Range("G5") & "_" & ActiveSheet.Name & ".pdf"
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
With OutlApp.CreateItem(0)
.Subject = Title
.To = Range("B4")
.CC = Range("G3")
.Body = "Hello " & Range("G5") & "," & vbLf & vbLf _
& "Your Summary is attached. If you have any further questions about your selections, please call 1-800-XXX-XXXX." & vbLf & vbLf _
& "Best Regards," & vbLf _
& Application.UserName & vbLf _
& "Implementation Specialist" & vbLf & vbLf
.Attachments.Add PdfFile
On Error Resume Next
.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0
End With
' Delete PDF file
Kill PdfFile
' Quit Outlook if it was created by this code
If IsCreated Then OutlApp.Quit
' Release the memory of object variable
Set OutlApp = Nothing
End Sub
I quickly wrote an example to show how to loop through the Data Validation List.
Sub Sample()
Dim ws As Worksheet
Dim acell As Range, DataValCell As Range, tmpRng As Range
Dim s As String
Dim MyAr As Variant
Dim i As Long
Set ws = Sheet1 '<~~> Change this to the relevant sheet
With ws
Set DataValCell = .Range("B2")
'~~> Handles =NamedRange or =$O$17:$O$18
If Left(DataValCell.Validation.Formula1, 1) = "=" Then
s = Mid(DataValCell.Validation.Formula1, 2)
Set tmpRng = .Range(s)
Else '~~> Handles aaa,bbb,ccc,ddd
s = DataValCell.Validation.Formula1
End If
If Not tmpRng Is Nothing Then '~~> Handles =NamedRange or =$O$17:$O$18
For Each acell In tmpRng.Cells
Debug.Print acell.Value
'~~> this is where you loop through the DV List
Next
Else '~~> Handles aaa,bbb,ccc,ddd
MyAr = Split(s, ",")
For i = LBound(MyAr) To UBound(MyAr)
Debug.Print MyAr(i)
'~~> this is where you loop through the DV List
Next i
End If
End With
End Sub

Emailing an Excel sheet as a PDF directly

My aim is to be able to click a button and for my Excel sheet to PDF a range of my spreadsheet and to email this to an email address which is in one of the cells in the sheet. For starters, I have the code which can turn a range of cells into a PDF file and allows me to save it:
Option Explicit
Sub savePDF()
Dim wSheet As Worksheet
Dim vFile As Variant
Dim sFile As String
Set wSheet = ActiveSheet
sFile = Replace(Replace(Range("D11"), " ", ""), ".", "_") _
& "_" _
& Range("H11") _
& ".pdf"
sFile = ThisWorkbook.Path & "\" & sFile
With Excel.Application.FileDialog(msoFileDialogSaveAs)
Dim i As Integer
For i = 1 To .Filters.Count
If InStr(.Filters(i).Extensions, "pdf") <> 0 Then Exit For
Next i
.FilterIndex = i
.InitialFileName = sFile
.Show
If .SelectedItems.Count > 0 Then vFile = .SelectedItems.Item(.SelectedItems.Count)
End With
If vFile <> "False" Then
wSheet.Range("A1:BF47").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
End Sub
Can anybody manipulate this code (attached to a button) so it will email an email address, which is in a particular cell, when the button is clicked and as an added bonus, have the subject of the email work from a cell in the spreadsheet too?
I have a solution which is below. After I set my print area by going into page payout and then set print area, I successfully managed to email the excel sheet as a PDF file:
Sub savePDFandEmail()
Dim strPath As String, strFName As String
Dim OutApp As Object, OutMail As Object
strPath = Environ$("temp") & "\" trailing "\"
strFName = ActiveWorkbook.Name
strFName = Left(strFName, InStrRev(strFName, ".") - 1) & "_" & ActiveSheet.Name & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
strPath & strFName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = Range("CB4")
.CC = Range("CB6")
.BCC = ""
.Subject = Range("CB8")
.Body = Range("BW11") & vbCr
.Attachments.Add strPath & strFName
'.Display 'Uncomment Display and comment .send to bring up an email window before sending
.Send 'Keep this the same if you want to send the email address out on click of the button
End With
Kill strPath & strFName
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
I also needed to put a little emailing tool into my sheet too which looks like this:
Clicking the button will now send the email with the PDF file attached.

Sending two PDFs by email

I made the code (as shown below) which send one PDF by email correctly, but I need to send one more PDF.
Dim varFindThis As Variant
Dim rngLookIn As Range
varFindThis = Worksheets("Suivi").Range("B1")
Set rngLookIn = Worksheets("Suivi").Range("A:A")
If Not rngLookIn.Find(varFindThis, LookIn:=xlValues) Is Nothing Then
Dim f As String
f = Worksheets("Suivi").Range("B1").Value
'Since i didn't got that clear, here above you must create a code to declare "f" as whatever you want
Set c = Worksheets("Suivi").Range("A:A").Find(f)
Worksheets("Suivi").Range(c.Address).EntireRow.Delete
End If
'Do not forget to change the email ID
'before running this code
Dim OlApp As Object
Dim NewMail As Object
Dim TempFilePath As String
Dim TempFileName As String
Dim FileFullPath As String
' With Application
' .ScreenUpdating = False
' .EnableEvents = False
' End With
Application.DisplayFullScreen = False
ThisWorkbook.Worksheets("PDF").Activate
Range("B1:BG46").Select
ActiveSheet.PageSetup.PrintArea = "$B$1:$BG$46"
' Temporary file path where pdf
' file will be saved before
' sending it in email by attaching it.
TempFilePath = Environ$("temp") & "\"
' Now append a date and time stamp
' in your pdf file name. Naming convention
' can be changed based on your requirement.
TempFileName = ActiveSheet.Name & "-" & Format(Now, "dd-mmm-20yy") & ".pdf"
'Complete path of the file where it is saved
FileFullPath = TempFilePath & TempFileName
'Now Export the Activesshet as PDF with the given File Name and path
On Error GoTo err
With ActiveSheet
.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=FileFullPath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
'Now open a new mail
Set OlApp = CreateObject("Outlook.Application")
'Loop through the rows
For Each cell In ThisWorkbook.Sheets("Envoie").Columns("C").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr1 = EmailAddr1 & ";" & cell.Value
End If
Next
For Each cell In ThisWorkbook.Sheets("Envoie").Columns("G").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr2 = EmailAddr2 & ";" & cell.Value
End If
Next
Subj = "N°Article" & ThisWorkbook.Sheets("CalculInfo").Range("A10")
Set NewMail = OlApp.CreateItem(0)
On Error Resume Next
With NewMail
.To = EmailAddr1
.CC = EmailAddr2
.BCC = "gaetan.affolter#he-arc.ch"
.Subject = Subj
.Body = "Bonjour, il vous reste 24 heures pour vérifier les données du PDF et de confirmer dans Octopus. Merci"
.Attachments.Add FileFullPath '--- full path of the pdf where it is saved
.Send 'or use .Display to show you the email before sending it.
End With
On Error GoTo 0
'Since mail has been sent with the attachment
'Now delete the pdf file from the temp folder
Kill FileFullPath
'set nothing to the objects created
Set NewMail = Nothing
Set OlApp = Nothing
'Now set the application properties back to true
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("Email a été envoyé")
Exit Sub
err:
MsgBox err.Description
Unload Me
The PrintArea I situated in the Worksheets("CalcGammeControle") and more precisely in "$G$2:$G$35"
How can I add it?

Export from Excel to Outlook

My workbook has 5 different sheets and I need to copy the five sheets and paste it into 5 different mails. Preferably as HTML.
The below written code only attaches the different sheets to outlook. I need the HTML below the body of the email. Please note that my range in the sheets varies from workbook to workbook but the sheet names remain the same.
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
'Function purpose: To Browser for a user selected folder.
'If the "OpenAt" path is provided, open the browser at that directory
'NOTE: If invalid, it will open at the Desktop level
'BrowseForFolder was a code originally written by Ron De Bruin, I love this function!
Dim ShellApp As Object
'Create a file browser window at the default folder
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
'Set the folder to that selected. (On error in case cancelled)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
'Destroy the Shell Application
Set ShellApp = Nothing
'Check for invalid or non-entries and send to the Invalid error
'handler if found
'Valid selections can begin L: (where L is a letter) or
'\\ (as in \\servername\sharename. All others are invalid
Select Case Mid(BrowseForFolder, 2, 1)
Case Is = ":"
If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
Case Is = "\"
If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
Case Else
GoTo Invalid
End Select
Exit Function
Invalid:
'If it was determined that the selection was invalid, set to False
BrowseForFolder = False
End Function
Sub SaveWorksheets()
'saves each worksheet as a separate file in a specific folder.
Dim ThisFolder As String
Dim NameOfFile As String
Dim Period As String
Dim RecipName As String
ThisFolder = BrowseForFolder()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim wsName As String
For Each ws In ActiveWorkbook.Worksheets
wsName = ws.Name
If wsName <> "Data" Then
Period = ws.Cells(4, 1).Value 'put the row and column numbers of the report date here.
RecipName = ws.Cells(1, 29).Value 'put the row and column numbers of the email address here
NameOfFile = ThisFolder & "\" & "Termination Report " & wsName & " " & Period & ".xlsx"
ws.Select
ws.Copy
ActiveWorkbook.SaveAs Filename:= _
NameOfFile, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
Call EmailWorkbooks(RecipName, NameOfFile)
End If
Next ws
End Sub
Sub EmailWorkbooks(RecipName, NameOfFile)
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.createItem(0)
Msg = "Attached is the xyz report for your review. Please let me know if you have any questions" & vbCrLf & vbCrLf _
& "Thanks," & vbCrLf & vbCrLf _
& "Your Name Here" & vbCrLf _
& "Your Title" & vbCrLf _
& "Your contact info"
Subj = "XYZ Report" & " " & Period
On Error Resume Next
With OutMail
.To = RecipName
'.CC =
.Subject = Subj
.Body = Msg
.Attachments.Add (NameOfFile)
.Save
End With
On Error GoTo 0
End Sub
U can use Add method of PublishObjects collection, short example:
Sub InsertSheetContent()
Dim onePublishObject As PublishObject
Dim oneSheet As Worksheet
Dim scriptingObject As Object
Dim outlookApplication As Object
Dim outlookMail As Object
Dim htmlBody As String
Dim htmlFile As String
Dim textStream
Set scriptingObject = CreateObject("Scripting.FileSystemObject")
Set outlookApplication = CreateObject("Outlook.Application")
For Each oneSheet In ThisWorkbook.Worksheets
htmlFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name & "_" & oneSheet.Name & ".html"
Set onePublishObject = ThisWorkbook.PublishObjects.Add(SourceType:=xlSourceRange, _
Filename:=htmlFile, _
Sheet:=oneSheet.Name, _
Source:=oneSheet.UsedRange.Address, _
HtmlType:=xlHtmlStatic, _
DivID:=oneSheet.Name)
onePublishObject.Publish Create:=True
Set textStream = scriptingObject.OpenTextFile(htmlFile)
htmlBody = textStream.ReadAll
Set outlookMail = outlookApplication.CreateItem(0)
With outlookMail
.htmlBody = htmlBody
.Display
End With
Next oneSheet
End Sub

Creating a leave absence system using Excel?

I'm totally new to Excel VBA. I am using Microsoft 2003 excel.
What my superior tasked me to do was to create a Leave Management System that tracks down an employee's amount of days left in terms of leave and from there, send an email down to her, her secretary and the employee regarding the status of approved or rejected.
I did try out some codes of VBA.. But I do not know how really the mail sending function works? Do i send the attachment out? Or when i entered some value in the code, it will auto send the whole attachment over? I'm really lost here, thank you!
Sub Mail_sheets()
Dim MyArr As Variant
Dim last As Long
Dim shname As Long
Dim a As Integer
Dim Arr() As String
Dim N As Integer
Dim strdate As String
For a = 1 To 253 Step 3
If ThisWorkbook.Sheets("mail").Cells(1, a).Value = "" Then
Exit Sub
End
Application.ScreenUpdating = False
last = ThisWorkbook.Sheets("mail").Cells(Rows.Count, _
a).End(xlUp).Row
N = 0
For shname = 1 To last
N = N + 1
ReDim Preserve Arr(1 To N)
Arr(N) = ThisWorkbook.Sheets("mail").Cells(shname, a).Value
Next shname
ThisWorkbook.Sheets(Arr).Copy
strdate = Format(Date, "dd-mm-yy") & " " & _
Format(Time, "h-mm-ss")
ActiveWorkbook.SaveAs "Part of " & ThisWorkbook.Name _
& " " & strdate & ".xls"
With ThisWorkbook.Sheets("mail")
MyArr = .Range(.Cells(1, a + 1), .Cells(Rows.Count, _
a + 1).End(xlUp))
End With
ActiveWorkbook.SendMail MyArr, ThisWorkbook.Sheets("mail").Cells(1, a + 2).Value
ActiveWorkbook.ChangeFileAccess xlReadOnly
Kill ActiveWorkbook.FullName
ActiveWorkbook.Close False
Application.ScreenUpdating = True
Next a
End Sub
Here is an example on how to achieve what you want. Please amend it for your actual needs.
I did try out some codes of VBA.. But I do not know how really the mail sending function works? Do i send the attachment out?
You don't need to send the entire workbook as an attachment. You can send a simple email stating whether the leave is approved or rejected. If you need to support why you are rejecting or approving the leave then you can paste the relevant cells in the email. See this example.
I am assuming for a moment that you worksheet looks like this.
Now suppose the employee Siddharth wants to take a leave. As we can see in the snapshot, the employee has 0 leaves balance. So the request for leave will be declined and a mail will be shot to the relevant person/Dept
When you run the code, it will ask you to enter the employees name
and then sends the relevant email.
CODE
Option Explicit
'~~> To Field in Email
Const strTo As String = "aaa#aaa.com"
'~~> CC field in email. If you do not want to CC then change "bbb#bbb.com" to ""
Const strCC As String = "bbb#bbb.com"
'~~> This is what goes in the body
Const strBody1 As String = "Dear XYZ,"
Const strBody2 As String = "This is in reference to leave request for employee "
Const strBodyApp As String = "The employee has sufficient leave balance and can take the leave"
Const strBodyNotApp As String = "The employee doesn't have sufficient leave balance and hence cannot take the leave"
Const strByeBye As String = "Thanks and Regards"
Const sender As String = "ABC"
Sub Sample()
Dim ws As Worksheet
Dim aCell As Range
Dim Ret
Dim Bal As Long
Dim Rw As Long
Ret = Application.InputBox("Please enter the name of the employee who wants to take a leave")
If Ret = "" Then Exit Sub
Set ws = Sheets("Sheet3")
Set aCell = ws.Columns(2).Find(What:=Ret, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Bal = aCell.Offset(, 5).Value
Rw = aCell.Row
If Bal > 0 Then
Approved Ret, True, Rw
Else
Approved Ret, False, Rw
End If
Else
MsgBox "The employee " & Ret & " was not found"
End If
End Sub
Sub Approved(EmpName, app As Boolean, lRow As Long)
Dim msg As String
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
If app = True Then
msg = "<p class=MsoNormal>" & strBody1 & "<o:p></o:p></p>" & vbNewLine & _
"<p class=MsoNormal><o:p> </o:p></p>" & vbNewLine & _
"<p class=MsoNormal>" & strBody2 & EmpName & ". " & strBodyApp & _
"<span style='mso-fareast-font-family:""Times New Roman""'><o:p></o:p></span></p>"
Else
msg = "<p class=MsoNormal>" & strBody1 & "<o:p></o:p></p>" & vbNewLine & _
"<p class=MsoNormal><o:p> </o:p></p>" & vbNewLine & _
"<p class=MsoNormal>" & strBody2 & EmpName & ". " & strBodyNotApp & _
"<span style='mso-fareast-font-family:""Times New Roman""'><o:p></o:p></span></p>"
End If
Set rng = Sheets("Sheet3").Range("A1:F1" & ",A" & lRow & ":F" & lRow)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = strTo
.CC = strCC
.BCC = ""
.Subject = "Leave Status"
.HTMLBody = msg & _
RangetoHTML(rng) & _
"<p class=MsoNormal><span style='mso-fareast-font-family:""Times New Roman""'>" & strByeBye & "<o:p></o:p></span></p>" & _
"<p class=MsoNormal><span style='mso-fareast-font-family:""Times New Roman""'><o:p> </o:p></span></p>" & _
"<p class=MsoNormal><span style='mso-fareast-font-family:""Times New Roman""'>" & sender & "<o:p></o:p></span></p>"
.Display '.Send 'To send the email
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
'~~> Taken from http://www.rondebruin.nl/mail/folder3/mail4.htm
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
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
DISCLAIMER: Since the above code is a basic example, I have not
1) included Error handling (which you should)
2) used basic stuff as Application.ScreenUpdating
SAMPLE FILE: This link will be active for the next 7 days. I have uploaded a sample file for you to play with :)
http://wikisend.com/download/562482/Sample.xls
HTH