Export selected PPT slides as a PDF attachment in outlook email - vba

See code below does work as a PPTX currently.
I need to have this export as a PDF not a PPTX and am having no luck. Help much appreciated! Also having no luck adding an email signature automatically to this code. Granted many users will end up using this macro.
Sub EmailFinal()
Dim objActivePresetation As Presentation
Dim objSlide As Slide
Dim n As Long
Dim strName As String
Dim strTempPresetation As String
Dim objTempPresetation As Presentation
Dim objOutlookApp As Object
Dim objMail As Object
Set objActivePresetation = ActivePresentation
For Each objSlide In objActivePresetation.Slides
objSlide.Tags.Delete ("Selected")
Next
'Add a tag "Selected" to the selected slides
For n = 1 To ActiveWindow.Selection.SlideRange.Count
ActiveWindow.Selection.SlideRange(n).Tags.Add "Selected", "YES"
Next n
strName = objActivePresetation.Name
strName = Left(strName, InStrRev(strName, ".") - 1)
strTempPresetation = Environ("TEMP") & "\" & strName & ".pptx"
'Copy the active presentation to a temp presentation
objActivePresetation.SaveCopyAs strTempPresetation
Set objTempPresetation = Presentations.Open(strTempPresetation)
'Remove the untagged slides
For n = objTempPresetation.Slides.Count To 1 Step -1
If objTempPresetation.Slides(n).Tags("Selected") <> "YES" Then
objTempPresetation.Slides(n).Delete
End If
Next n
objTempPresetation.Save
objTempPresetation.Close
'Attach the temp presentation to a new email
Set objOutlookApp = CreateObject("Outlook.Application")
Set objMail = objOutlookApp.CreateItem(olMailItem)
'Change the email details as per your needs
With objMail
.To = "insertemailhere"
.Subject = strName
.Body = "Dear Company," & vbCr & vbCr & "Please see attached Plaques.," & vbCr & "Please let me know if you need any further assistance."
.Attachments.Add strTempPresetation
.Display
End With
End Sub
Thank You!!

Use the Presentation.ExportAsFixedFormat method.
Instead of objTempPresetation.Save do objTempPresetation.ExportAsFixedFormat and specify your desired parameters but at least specify those parameters:
objTempPresetation.ExportAsFixedFormat Path:="C:\yourpath\yourfile.pdf", FixedFormatType:=ppFixedFormatTypePDF
other parameters are optional.

Related

copy paragraph from multiline texbox form to outlook

I have a form with a multiline texbox, when I write a paragraph and try to copy it to outlook just as It looks in texbox with the spaces between lines but it copy all the paragraph in one line. You can see it in the images. I know that I can write the paragraph in HTML code in .HTMLBody, but that's not what I want because I want to edit that anytime I send a mail. I don't know if there is a code to do that, if not could you give me some other ideas?
Form_Enviar_Correo
Outlook Mail
Sub ENVIAR()
Dim a As Worksheet, b As Worksheet
Dim OApp As Object, OMail As Object, sbdy As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
ChDir (ActiveWorkbook.Path)
Dest = Form_Enviar_Correo.Txt_Para.Value
Asun = Form_Enviar_Correo.Txt_Asunto.Value
CC = Form_Enviar_Correo.Txt_CC.Value
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
spie = "<img align=left width=80 height=90 src=https://xxxxxxxxxxxxx.png>"
sbdy = spie
With OMail
.To = Dest
.CC = CC
'.BCC = SCop
.Subject = Asun
.Body = Form_Enviar_Correo.Txt_Cuerpo.Text
.HTMLBody = sbdy
.Display
'.Send
End With
Set OMail = Nothing
Set OApp = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
'MsgBox ("El mensaje se envió con éxito"), vbInformation, "AVISO"
End Sub
Assuming the lines are separated by a carriage return vbCr you can just replace them all with the HTML equivalent with one line of code using the Replace function.
Dim sText as String
sTest = "This is" & vbCr & "a test"
MsgBox sTest
Dim sHTMLFormat as String
sHTMLFormat = Replace(sTest, vbCr, "<br>")
MsgBox sHTMLFormat
so...
.HTMLBody = Replace(Form_Enviar_Correo.Txt_Cuerpo.Text, vbCr, "<br>")
They may also be separated by vbNewLine or vbCrLf or vbLf so use the one that works in your case.

Can I create and save a signature as default in Outlook through VBA?

I have made some progress and hence editing my description
I have a .xls file with signature that user save.
User clicks a custom button which opens a FileDialog from where he searches and selects the signature file. The code extracts the signature from the xls file and creates an HTML file in "AppData/Roaming/Microsoft/Signatures". My code works uptill this part--it opens the file and extracts the signature portion, creates HTML, the signature option is visible in the Signature Menu in Outlook. But when i click the mode-generated signature option, it is not displayed in the mail body.
I compared it with a manually created Signature in Outlook and after comparing the 2 HTML files, I feel this portion is causing the problem.
The marked portion is in the manually created signature but not in my code generated one. My inference is I am not creating a signature type HTML file as such. Can anyone help me with this? And my initial question still remains how do I make my code generated signature the default one?
My Code is as follows:
Option Explicit
Public Sub MailSignatur2()
Dim SigFolder2 As String
Dim fd As Office.FileDialog
Dim selectedItem As Variant
Dim SigFolder As String
Dim ExcelFileName As String
Dim FileName As String
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim Signature As String
Dim oMsg As MailItem
Dim c As Variant
Dim fso As New FileSystemObject
Dim saveFolder As String
Dim DateFormat As String
Dim objSign As MailItem
SigFolder2 = "C:\Users\" & Environ("UserName") & "\Downloads\"
Debug.Print SigFolder2
Set fd = objExcel.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.InitialFileName = SigFolder2
.AllowMultiSelect = False
.Title = "Select Signature File"
End With
If fd.Show = -1 Then
For Each selectedItem In fd.SelectedItems
SigFolder = selectedItem
Next
Else
Exit Sub
End If
ExcelFileName = SigFolder
FileName = Left(fso.GetFileName(ExcelFileName), InStr(fso.GetFileName(ExcelFileName), ".") - 1)
Debug.Print ExcelFileName
Debug.Print FileName
Set exWb = objExcel.Workbooks.Open(ExcelFileName)
Signature = vbNullString
For Each c In exWb.Sheets(FileName).Range("A1:A30")
If c.Value = "$" Then
Exit For
Else
If c.Value = "%" Then
Signature = Signature & "<hr align='left' width='20%'><br>"
Else
Signature = Signature & c.Value & "<br>"
End If
End If
Next c
On Error Resume Next
Set oMsg = ActiveInspector.CurrentItem
On Error GoTo 0
Set objSign = Application.CreateItem(olMailItem)
With objSign
.HTMLBody = "<html><body><div><p>" & Signature & "</p></div></body></html>"
End With
saveFolder = "C:\Users\" & Environ("UserName") & "\AppData\Roaming\Microsoft\Signatures\"
objSign.SaveAs saveFolder & "Official_Sign.html", olHTML
Debug.Print saveFolder
ExitRoutine:
Set oMsg = Nothing
Set exWb = Nothing
Set objExcel = Nothing
End Sub
Got it. Very small mistake.It should be .htm instead of .html
objSign.SaveAs saveFolder & "Official_Sign.htm", olHTML

Embedding Several Images into an Email using VBA from Excel to Outlook and using CID

I'm trying to embed several graphs (as PNGs) from a Excel VBA Macro to Outlook.
The images embed however, it's not all 8 images but the first one repeated 8 times.
Sub Test()
Dim sheetNumber, size, i As Integer
Dim chartNames(), FNames() As String
Dim objChrt As ChartObject
Dim myChart As Chart
'Activate Charts Sheet
Sheets("GRAFICAS").Activate
'Calculate Number of Charts in Sheet
chartNumber = ActiveSheet.ChartObjects.Count
'Redimension Arrays to fit all Chart Export Names
ReDim chartNames(chartNumber)
ReDim FNames(chartNumber)
'Loops through all the charts in the GRAFICAS sheet
For i = 1 To chartNumber
'Select chart with index i
Set objChrt = ActiveSheet.ChartObjects(i)
Set myChart = objChrt.Chart
'Generate a name for the chart
chartNames(i) = "myChart" & i & ".png"
On Error Resume Next
Kill ThisWorkbook.Path & "\" & chartNames(i)
On Error GoTo 0
'Export Chart
myChart.Export Filename:=Environ$("TEMP") & "\" & chartNames(i), Filtername:="PNG"
'Save path to exported chart
FNames(i) = Environ$("TEMP") & "\" & chartNames(i)
Next i
'Declare the Object variables for Outlook.
Dim objOutlook As Object
'Verify Outlook is open.
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
'If Outlook is not open, end the Sub.
If objOutlook Is Nothing Then
Err.Clear
MsgBox _
"Cannot continue, Outlook is not open.", , _
"Please open Outlook and try again."
Exit Sub
'Outlook is determined to be open, so OK to proceed.
Else
'Establish an Object variable for a mailitem.
Dim objMailItem As Object
Set objMailItem = objOutlook.CreateItem(0)
'Build the mailitem.
Dim NewBody As String
On Error Resume Next
With objMailItem
.To = "dummy#test.com"
.Subject = "Testing Lesson 31 email code"
.Importance = 1 'Sets it as Normal importance (Low = 0 and High = 2)
'Change the Display command to Send without reviewing the email.
' .Display
End With
For i = 1 To chartNumber
objMailItem.Attachments.Add FNames(i)
'Put together the HTML to embed
NewBody = NewBody + HTMLcode & "<div align=center>" & "<IMG src=cid: myChart" & i & ".png></img>" & "</div>"
Next
MsgBox NewBody
'Set the HTML body
objMailItem.HTMLBody = NewBody
'Display email before sending
objMailItem.Display
'Close the If block.
End If
Kill Fname
End Sub
MsgBox NewBody outputs:
and the final email looks like:
It should show all charts one below the other one, however it only takes myChart1.png and repeats it 8 times, despite the output of NewBody.
What am I doing wrong? I'm using Outlook 2013 and Excel 2013
UPDATE: I added another image and it seems to, in this case, repeat the last image I added 9 times (same as number of attached images). I'm guessing it's a problem with the cid, maybe ids aren't unique?
You must set the PR_ATTACH_CONTENT_ID property on the attachment appropriately to match the value of the cid attribute:
Set attach = objMailItem.Attachments.Add(FNames(i))
'Put together the HTML to embed
Dim cid
cid = "myChart" & i & ".png"
NewBody = NewBody + HTMLcode & "<div align=center>" & "<IMG src=cid:" & cid & "</img>" & "</div><br><br>"
Call attach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", cid)

How do I loop through a specific folder in outlook

What would be the VBA code for looping through a specific folder in outlook 2010 that is NOT the default inbox nor a subfolder of the inbox?
Dim ns As Outlook.NameSpace
Dim folder As MAPIFolder
Set ns = Session.Application.GetNamespace("MAPI")
Set folder = Please help me :-)
Thank you for any hint and help, greetings Ionic
Change
Set ns = Session.Application.GetNamespace("MAPI")
To
Set ns = Session.Application.GetNamespace("MAPI").PickFolder
This will prompt you to select the folder.
Here's a full routine that I wrote some time ago that may be of assistance, bear in mind this was written so that it could be run from Excel but should provide you with the syntax that you need:
Sub GetMail()
'// This sub is designed to be used with a blank worksheet. It will create the header
'// fields as required, and continue to populate the email data below the relevant header.
'// Declare required variables
'-------------------------------------------------------------
Dim olApp As Object
Dim olFolder As Object
Dim olMailItem As Object
Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim strBody As String
Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
'-------------------------------------------------------------
'//Turn off screen updating
Application.ScreenUpdating = False
'//Setup headers for information
Range("A1:F1").Value = Array("To", "From", "Subject", "Body", "Sent (from Sender)", "Received (by Recipient)")
'//Format columns E and F to
Columns("E:F").EntireColumn.NumberFormat = "DD/MM/YYYY HH:MM:SS"
'//Create instance of Outlook
Set olApp = CreateObject("Outlook.Application")
'//Select folder to extract mail from
Set olFolder = olApp.GetNamespace("MAPI").PickFolder
'//Get count of mail items
totalItems = olFolder.items.Count
mailCount = 0
'//Loop through mail items in folder
For Each loopControl In olFolder.items
'//If loopControl is a mail item then continue
If TypeName(loopControl) = "MailItem" Then
'//Increase mailCount
mailCount = mailCount + 1
'//Inform user of item count in status bar
Application.StatusBar = "Reading email no. " & mailCount & " of " & totalItems
'//Get mail item
Set olMailItem = loopControl
'//Get Details
With olMailItem
strTo = .To
'//If strTo begins with "=" then place an apostrophe in front to denote text format
If Left(strTo, 1) = "=" Then strTo = "'" & strTo
strFrom = .Sender
'//If sender displays name only, show name followed by email address e.g.(Bloggs, Joe < j.bloggs#mail.com >)
If InStr(1, strFrom, "#") < 1 Then strFrom = strFrom & " - < " & .SenderEmailAddress & " >"
dateSent = .SentOn
dateReceived = .ReceivedTime
strSubject = .Subject
strBody = .Body
End With
'//Place information into spreadsheet
'//import information starting from last blank row in column A
With Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
.Value = strTo
.Offset(0, 1).Value = strFrom
.Offset(0, 2).Value = strSubject
'//Check for previous replies by looking for "From:" in the body text
'//Check for the word "From:"
If InStr(0, strBody, "From:") > 0 Then
'//If exists, copy start of email body, up to the position of "From:"
.Offset(0, 3).Value = Mid(strBody, 1, InStr(1, strBody, "From:") - 1)
Else
'//If doesn't exist, copy entire mail body
.Offset(0, 3).Value = strBody
End If
.Offset(0, 4).Value = dateSent
.Offset(0, 5).Value = dateReceived
End With
'//Release item from memory
Set olMailItem = Nothing
End If
'//Next Item
Next loopControl
'//Release items from memory
Set olFolder = Nothing
Set olApp = Nothing
'//Resume screen updating
Application.ScreenUpdating = True
'//reset status bar
Application.StatusBar = False
'//Inform user that code has finished
MsgBox mailCount & " messages copied successfully.", vbInformation, "Complete"
End Sub
Okay, I've found it myself.
Set folder = ns.GetDefaultFolder(olFolderInbox).Parent.Folders(NAME OF THE FOLDER)
Than you for your help guys !

VBA retrieve HTMLBody from Outlook mail

First I create an email via Outlook:
Sub CreateHTMLMail()
'Creates a new e-mail item and modifies its properties.
Dim olApp As Outlook.Application
Dim objMail As Outlook.MailItem
Set olApp = Outlook.Application
'Create e-mail item
Set objMail = olApp.CreateItem(olMailItem)
Dim sHTML_Open As String
Dim sHTML_Introduction As String
Dim sHTML_Goodbye As String
Dim sHTML_Close As String
Dim sHTML_Process_Date As String
Dim sHTML_Processor As String
Dim sHTML_Issuer As String
Dim sHTML_Details As String
Dim sHTML_Body As String
sHTML_Open = "<HTML><BODY>"
sHTML_Introduction = "Hi team,<BR/><BR/>" & _
"Data is ready to process. Please find details as below.<BR/>"
sHTML_Process_Date = "<P ID='PROCESSDATE'>28 February 2013</P>"
sHTML_Processor = "<P ID='PROCESSOR'>AKSHAY</ID></P>"
sHTML_Issuer = "<P ID='ISSUER'>DATAGROUP.COM</ID></P>"
sHTML_Details = "<P ID='DETAILS'>" & _
"<UL>" & _
"<LI>Fimta23456 09:00:00 flor345</LI>" & _
"<LI>Fimta23456 09:00:00 flor345</LI>" & _
"</UL>" & _
"</P><BR/>"
sHTML_Goodbye = "Thanks"
sHTML_Close = "</BODY></HTML>"
sHTML_Body = sHTML_Open & sHTML_Introduction & sHTML_Process_Date & sHTML_Processor & sHTML_Issuer & _
sHTML_Details & sHTML_Goodbye & sHTML_Close
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.To = "Kim Gysen"
.Subject = "data remit file"
.HTMLBody = sHTML_Body
.Display
End With
End Sub
Via code, I want to retrieve values based on ID.
This seemed the cleanest way for me, I don't particulary like the "split" method because it's kind of hard coding; not very dynamic and kinda unreliable.
Unfortunately when I retrieve the HTML body, I cannot retrieve the original HTML, as it is distorted by Outlook:
Sub Get_OL()
Dim oFolder As MAPIFolder
Dim oItem As Variant
Dim sHTML_Body As String
Dim sHTML_Process_Date As String
Dim sHTML_Processor As String
Dim sHTML_Issuer As String
Dim sHTML_Details As String
Dim oExcel As Object
Dim oBook As Workbook
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
'Access the outlook inbox folder
Set oFolder = GetNamespace("MAPI").PickFolder
'On error resume next usually not to use, but feteching emails may give unexpected errors
On Error Resume Next
For Each oItem In oFolder.Items
If TypeOf oItem Is Outlook.MailItem Then
If oItem.Subject Like "*data remit file*" Then
'Turn off on error resume next asap
On Error GoTo 0
sHTML_Body = oItem.HTMLBody
Debug.Print sHTML_Body
Exit For
End If
End If
Next oItem
End Sub
On debug.print, this is what I get (only putting the last line of the Format):
</o:shapelayout></xml><![endif]--></head><body lang=EN-GB link=blue vlink=purple><div class=WordSection1><p class=MsoNormal>Hi team,<br><br>Data is ready to process. Please find details as below.<br><br><o:p></o:p></p><p>28 February 2013<o:p></o:p></p><p id=PROCESSOR>AKSHAY<o:p></o:p></p><p id=ISSUER>DATAGROUP.COM<o:p></o:p></p><ul type=disc><li class=MsoNormal style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto;mso-list:l0 level1 lfo1'>Fimta23456 09:00:00 flor345<o:p></o:p></li><li class=MsoNormal style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto;mso-list:l0 level1 lfo1'>Fimta23456 09:00:00 flor345<o:p></o:p></li></ul><p class=MsoNormal><br>Thanks<o:p></o:p></p></div></body></html>
I would like to retrieve the original HTML that I put in the HTMLBody.
2 ways:
1) parsing text - several things to do (not recommended: hard-coding)
All what you need is to parse text, but MSDN shows how to do it using InStr function. I would strongly suggest to use RegEx to parse html text. Note: reference to MS VBScript Regular Expressions x.x is needed.
Simple Regular Expression Tutorial for Excel VBA
2) using UserProperites of MailItem object (recommended)
If MailItem doesn't contains your propert(y)ies, than there is nothing to do ;)
How to: Add custom property