• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Copying Active Sheet in Email Body / RondeBruin RangetoHTML function|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / Copying Active Sheet in Email Body / RondeBruin RangetoHTML function|VBA & Macros|Excel Forum|My Online Training Hub

Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosCopying Active Sheet in Email Body …
sp_PrintTopic sp_TopicIcon
Copying Active Sheet in Email Body / RondeBruin RangetoHTML function
Avatar
Alexandra Duboc

New Member
Members
Level 0
Forum Posts: 2
Member Since:
August 2, 2018
sp_UserOfflineSmall Offline
1
August 2, 2018 - 8:10 pm
sp_Permalink sp_Print

Hi Everyone, 

Thanks a lot for this forum and all those helpful posts - a truly great bunch of talented people !!

I've been trying to get a code to 

1) Save my Active Worksheet into a Pdf file with a pre-determined name

2) Attach it to an email with pre-determined subject, Email-To and Email- CC 

3) Copy part of the worksheet into the Email Body 

I've managed to get the first two running but I just can't get my Email Body to work. 

I've used this great post by Philip Treacy as well as Ron de Bruin's RangetoHTML function and tried to combine the two but when I try to run it I get a 91 type Error - Undefined Variable. 

The Debugor points to the line : rng.Copy, which to me is not a variable but a command action, as rng is defined at least twice in the code before. 

Here is the complete code : 

Private Sub CommandButton1_Click()

Application.ReferenceStyle = xlA1

Dim EmailSubject As String, EmailSignature As String

Dim Email_Body As String

Dim CurrentMonth As String, DestFolder As String, PDFFile As String

Dim Email_To As String, Email_CC As String, Email_BCC As String

Dim OpenPDFAfterCreating As Boolean, AlwaysOverwritePDF As Boolean, DisplayEmail As Boolean

Dim OverwritePDF As VbMsgBoxResult

Dim rng As Range

Dim OutlookApp As Object, OutlookMail As Object

CurrentMonth = ""

' *****************************************************

' ***** You Can Change These Variables *********

EmailSubject = "Emergence Actions (FR0011742683) - Amortissement en capital - ACMN - " 'Change this to change the subject of the email. The current month is added to end of subj line

OpenPDFAfterCreating = False 'Change this if you want to open the PDF after creating it : TRUE or FALSE

AlwaysOverwritePDF = False 'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE

DisplayEmail = True 'Change this if you don't want to display the email before sending. Note, you must have a TO email address specified for this to work

Email_To = ActiveSheet.Range("J10") 'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1

Email_CC = ""

Email_BCC = ""

Email_Body = RangetoHTML(rng)

 

' ******************************************************

'Prompt for file destination

With Application.FileDialog(msoFileDialogFolderPicker)

If .Show = True Then

DestFolder = .SelectedItems(1)

Else

MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"

Exit Sub

End If

End With

'Current month/year stored in H6 (this is a merged cell)

CurrentMonth = Mid(ActiveSheet.Range("H6").Value, InStr(1, ActiveSheet.Range("H6").Value, " ") + 1)

'Create new PDF file name including path and file extension

PDFFile = DestFolder & Application.PathSeparator & "Emergence Actions - Amortissement en Capital - ACMN " _

& "_" & CurrentMonth & ".pdf"

'If the PDF already exists

If Len(Dir(PDFFile)) > 0 Then

If AlwaysOverwritePDF = False Then

OverwritePDF = MsgBox(PDFFile & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", vbYesNo + vbQuestion, "File Exists")

On Error Resume Next

'If you want to overwrite the file then delete the current one

If OverwritePDF = vbYes Then

Kill PDFFile

Else

MsgBox "OK then, if you don't overwrite the existing PDF, I can't continue." _

& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"

Exit Sub

End If

Else

On Error Resume Next

Kill PDFFile

End If

If Err.Number 0 Then

MsgBox "Unable to delete existing file. Please make sure the file is not open or write protected." _

& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"

Exit Sub

End If

End If

Debug.Print PDFFile

'Create the PDF

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _

:=False, OpenAfterPublish:=OpenPDFAfterCreating

'Create an Outlook object and new mail message

Set OutlookApp = CreateObject("Outlook.Application")

Set OutlookMail = OutlookApp.CreateItem(0)

'Create the email body

Set rng = Nothing

On Error Resume Next

Set rng = Sheets("Amort 1").Range("A23:E43").SpecialCells(xlCellTypeVisible)

'Display email and specify To, Subject, etc

With OutlookMail

.Display

.To = Email_To

.CC = Email_CC

.BCC = Email_BCC

.Subject = EmailSubject & CurrentMonth

.Attachments.Add PDFFile

If DisplayEmail = False Then

.Send

End If

End With

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

 

I am a complete beginner in VBA and find myself at my wits ends. 

 Many thanks in advance to anyone who could help me. 

Best !

sp_AnswersTopicSeeAnswer See Answer
Avatar
Philip Treacy
Admin
Level 10
Forum Posts: 1463
Member Since:
October 5, 2010
sp_UserOfflineSmall Offline
2
August 6, 2018 - 8:57 am
sp_Permalink sp_Print

Hi Alexandra,

You are calling the RangetoHTML function and passing in rng, but rng has no value, hence the error you are getting.

Also, whatever RangetoHTML returns is not actually being added to the email body.

I've corrected both of these things so the attached workbook works for me.

Just comment out my line Set rng = Range("A1:C2") and uncomment yours.

Regards

Phil

sp_AnswersTopicAnswer
Answers Post
Avatar
Alexandra Duboc

New Member
Members
Level 0
Forum Posts: 2
Member Since:
August 2, 2018
sp_UserOfflineSmall Offline
3
August 7, 2018 - 12:39 am
sp_Permalink sp_Print

It worked ! And I think I understand where I went wrong. 

Thank you for taking the time, I really appreciate it.

 

Best ! 

Avatar
Philip Treacy
Admin
Level 10
Forum Posts: 1463
Member Since:
October 5, 2010
sp_UserOfflineSmall Offline
4
August 7, 2018 - 8:30 am
sp_Permalink sp_Print

You're welcome.

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 170
Currently Online: Bouskila stephanie, James Hwang
Guest(s) 50
Currently Browsing this Page:
1 Guest(s)
Top Posters:
SunnyKow: 1431
Anders Sehlstedt: 848
Velouria: 574
Purfleet: 412
Frans Visser: 346
David_Ng: 306
lea cohen: 213
A.Maurizio: 202
Aye Mu: 201
Jessica Stewart: 185
Newest Members:
David Collins
Andras Marsi
Orimoloye Funsho
YUSUF IMAM KAGARA
PRADEEP PRADHAN
Vicky Otosnika
Abhishek Singh
Kevin Sojourner
Kara Weiss
And Woox
Forum Stats:
Groups: 3
Forums: 24
Topics: 6047
Posts: 26543

 

Member Stats:
Guest Posters: 49
Members: 31497
Moderators: 2
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: MOTH Support, Riny van Eekelen
© Simple:Press —sp_Information
  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
 
  • About My Online Training Hub
  • Contact
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Copyright © 2023 · My Online Training Hub · All Rights Reserved

Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.

Download A Free Copy of 100 Excel Tips & Tricks

excel tips and tricks ebook

We respect your privacy. We won’t spam you.

x