• 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
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • 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
You are here: Home

vba course banner

Lost password?
sp_Search
Advanced Search
Advanced Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search

Please confirm you want to mark all posts read

Mark all topics read

sp_MobileMenu Actions
Actions
sp_LogInOut
Log In
sp_Search

Search Forums

sp_RankInfo
Ranks Information
Avatar

New/Updated Topics

General Excel Questions & Answers

  Split Names

  Buttons and Combo Boxes Graphics Issues on different Compute…

  Formula for Drawdown

  Use remaining balance from the past 3 years upto a maximum a…

  Time in Hrs

  Conditionally format calendar based on list

Dashboards & Charts

  Grand Totals on Pivot Charts

  Line Chart showing up as dots and not lines

VBA & Macros

  Add ".xlsb" to existing Macro - IF Statement

  Help with VBA for Store Quantity Management

Power Query

  Rolling Year to Date Value for Each Operating Area

  Table Sort

Excel Dashboards

  Blank Entries in Slicer

Power BI

  Power BI - formula

Select Forum

  Rules and Guides

Forum Rules and Guides

  Public Forums - For Registered Users

General Excel Questions & Answers

Dashboards & Charts

VBA & Macros

Power Query

Power Pivot

  Course Members Only

Excel Dashboards

Power Query

Power Pivot

Xtreme Pivot Tables

Excel for Decision Making

Excel for Finance

Power BI

Excel

Word

Outlook

Excel Expert

Excel for Customer Service Professionals

Excel Analysis Toolpak

Excel Tables

Excel for Operations Management

Financial Modelling

Advanced Excel Formulas

Pivot Tables Quick Start

ForumsVBA & Macros
sp_TopicIcon
Copying Active Sheet in Email Body / RondeBruin RangetoHTML function
Avatar
Alexandra Duboc
Posts: 2

Level 0
August 2, 2018 - 8:10 pm

1

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
Avatar
Philip Treacy
Posts: 1529
Level 10
August 6, 2018 - 8:57 am

2

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
Avatar
Alexandra Duboc
Posts: 2

Level 0
August 7, 2018 - 12:39 am

3

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
Posts: 1529
Level 10
August 7, 2018 - 8:30 am

4

You're welcome.

Forum Timezone:
Australia/Brisbane
Most Users Ever Online: 245
Currently Online: David Jernigan, Louis Muti
Guest(s) 7
Currently Browsing this Page:
1 Guest(s)

Devices in use: Desktop (7), Phone (2)

Forum Stats:
Groups: 3
Forums: 24
Topics: 6359
Posts: 27806
Member Stats:
Guest Posters: 49
Members: 32336
Moderators: 3
Admins: 4
© Simple:Press

Sidebar

Blog Categories

  • 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
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

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.