VBA to Copy specified worksheets into a new workbook and attach to email

Mindb85

New Member
Joined
Sep 20, 2016
Messages
6
Hello,

I have the attached code which pretty much does what I want but I require assistance in changing it so that it no longer produces a PDF but instead attaches the specified worksheets as .xls files.

Any assistance would be greatly appreciated

Code:
Sub Attach_Sheets_As_Pdf_With_Signature()
' ZVI:2016-09-20 [URL]http://www.mrexcel.com/forum/excel-questions/710212-visual-basic-applications-code-convert-excel-pdf-email-attachment-5.html#post4636678[/URL]
 
  ' --> User settings, change to suit
  Const MySheets As Variant = "SUMMARY,PAYROLL,MILEAGE,OVERTIME" ' Use MySheets = 0 for all the sheets
  Const IsDisplay As Boolean = True           ' Change to False to .Send instead of .Display
  Const IsSilent As Boolean = True           ' Change to True to Send without the confirmation MsgBox
  ' <-- End of settings
 
  Dim IsCreated As Boolean
  Dim PdfFile As String, Signature As String
  Dim OutlApp As Object
  Dim i As Long
  Dim char As Variant
 
  ' Define PDF filename
  PdfFile = ActiveWorkbook.Name
  i = InStrRev(PdfFile, ".xl", , vbTextCompare)
  If i > Len(PdfFile) - 5 Then PdfFile = Left(PdfFile, i - 1)
  PdfFile = PdfFile & "_" & ActiveSheet.Name
  ' Clean up the name of PDF file
  For Each char In Split("? "" / \ < > * | :")
    PdfFile = Replace(PdfFile, char, "_")
  Next
  ' Add %TEMP% path to the file name and limit too long name
  PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "" & PdfFile, 251) & ".pdf"
 
  ' Try to delete PDF file for the case it was not deleted at debugging
  If Len(Dir(PdfFile)) Then Kill PdfFile
 
  ' Select sheets to be exported in the PDF (single) file
  If MySheets = 0 Then
    ' All sheets to PDF
    Sheets.Select
  Else
    ' Sheets listed in MySheets to PDF
    Sheets(Split(MySheets, ",")).Select
  End If
 
  ' Export the selected sheets as PDF to the temporary folder
  With ActiveSheet
    .ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
    .Select
  End With
 
  ' Use the already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  On Error GoTo 0
 
  ' Prepare email with PDF attachment and default signature
  With OutlApp.CreateItem(0)
  
    ' Add the attachment first for correct attachment's name with non English symbols
    .Attachments.Add PdfFile
  
   ' Get default email signature without blinking (instead of .Display method)
    With .GetInspector: End With
    Signature = .HTMLBody
 
    ' Prepare e-mail (uncommenmt and fill the lines below)
    .Subject = "Staffing"
    .To = Range("I3").Value
    .CC = Range("I4").Value
     Message = "****** style=font-size:11.5pt;font-family:GillSansMT>Hi" & vbLf & vbLf _
            & "****** style=font-size:11.5pt;font-family:GillSansMT>Please find attached the Payroll Monitoring for your relevant departments to " & Sheets("LkUps").Range("C5").Value & ". This will be reflected in the " & Sheets("LkUps").Range("C5").Value & " Budget Monitoring Statement. The attached documents show the overall total payroll costs together with a summary of any overtime and mileage payments made." & vbLf & vbLf _
            & "****** style=font-size:11.5pt;font-family:GillSansMT>It is important that you let us know if anything is incorrect as soon as possible so we can correct it in time for budget monitoring.  If you have any queries, please contact a member of the Finance Team. The format has changed slightly and we are now sending it out as a pdf, as this allows us to work more efficiently and therefore send it out before budget monitoring.  If this creates any problems please let me know and I will try to resolve them." & vbLf & vbLf _
            & "****** style=font-size:11.5pt;font-family:GillSansMT>Kind Regards"
    .HTMLBody = Replace(Message, vbLf, Chr(60) & "br" & Chr(62)) & Signature
  
    ' Try to send or just display the e-mail
    On Error Resume Next
    If IsDisplay Then .Display Else .Send
  
    ' Show error of .Send method
    If Not IsDisplay Then
      ' Return focus to Excel's window
      Application.Visible = True
      ' Report on error or success
      If Err Then
        MsgBox "E-mail was not sent for some reasons" & vbLf & "Please check it", vbExclamation
        .Display
      Else
        If Not IsSilent Then
          MsgBox "E-mail successfully sent", vbInformation
        End If
      End If
    End If
    On Error GoTo 0
 
  End With
 
  ' Delete the temporary PDF file
  If Len(Dir(PdfFile)) Then Kill PdfFile
 
  ' Try to quit Outlook if it was not previously open
  If IsCreated Then OutlApp.Quit
 
  ' Try to release the memory of object variable
  Set OutlApp = Nothing
 
End Sub

Regards

Will
 

Excel Facts

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
Change the type from xlTypePDF to xlTypeXPS

Code:
' Export the selected sheets as PDF to the temporary folder
With ActiveSheet
     .ExportAsFixedFormat Type:=xlTypeXPS, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
.Select
End With
 
Last edited:
Upvote 0
Change the type from xlTypePDF to xlTypeXPS

Code:
' Export the selected sheets as PDF to the temporary folder
With ActiveSheet
     .ExportAsFixedFormat Type:=xlTypeXPS, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
.Select
End With

Do I need to adjust anything else? It is coming back with the following error message

Run-time error '-2147024894(80070002)':

Cannot find this file. Verify the path and file name are correct.


Regards

Will
 
Upvote 0
Replace:

Code:
PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "" & PdfFile, 251) & ".pdf"

With:

Code:
PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "" & PdfFile, 251) & ".xlsm"
 
Upvote 0
I have amended the code as above however it is still returning the same error message.

when I go into Debug mode it is highlighting .Attachments.Add PdfFile

Do you have any further suggestions?

Regards

Will
 
Upvote 0

Forum statistics

Threads
1,214,576
Messages
6,120,354
Members
448,956
Latest member
Adamsxl

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top