Set Focus Back to Excel, Mac VBA 2016 - excel

I am currently using the following VBA code in Excel for MAC 2016:
Sub MailWorkSheet()
Dim SourceWb As Workbook, DestWb As Workbook, sh As Worksheet
Dim strbody As String, TempFileName As String
If Val(Application.Version) < 15 Then Exit Sub
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Check if the Script File is in the correct location
If CheckScript(ScriptFileName:="ExcelOutlook.scpt") = False Then
MsgBox "Sorry the ExcelOutlook.scpt file is not in the correct
location, " & _
"Email File Manually."
Exit Sub
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Set reference to the source workbook
Set SourceWb = ActiveWorkbook
'Create the body text in the strbody string
strbody = "<FONT size=""3"" face=""Calibri"">"
strbody = strbody & "Hello:" & "<br>" & "<br>" & _
"XXXXXXX." & "<br>" & _
" " & "<br>" & _
"XXXXXXX." & "<br>" & _
" " & "<br>" & _
"XXXXXXX!!"
strbody = strbody & "</FONT>"
'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set DestWb = ActiveWorkbook
'Delete the button on the one sheet workbook
On Error Resume Next
DestWb.Sheets(1).DrawingObjects.Visible = True
DestWb.Sheets(1).DrawingObjects.Delete
On Error GoTo 0
'Enter the name of the file just created
TempFileName = "Long Lane Merit Sheet" & " " _
& Range("A2") & " " & Format(Now, "mmm-dd-yy")
'Call the MailWithMac function to save the new file and create the
mail
MailWithMac _
subject:="XXXXXXX", _
mailbody:=strbody, _
toaddress:=Range("A3"), _
ccaddress:="", _
bccaddress:="", _
displaymail:=True, _
accounttype:="", _
accountname:="", _
attachment:=TempFileName, _
FileFormat:=SourceWb.FileFormat
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
'Turn on Automatic Calculation
Application.Calculation = xlCalculationAutomatic
'Turn Alert Messages On
Application.DisplayAlerts = True
End Sub
It works great to email the current sheet through Outlook.
The problem I am having is that I want the focus to return to the Excel sheet. What is happening now is that the Outlook screen along with a new email pops up. After hitting send, the new email screen goes away, but the main Outlook window remains.
How do I set focus back to Excel?

I have found that the solution is to use Applescript to achieve the desired effect. Here is the whole script:
ption Explicit
Sub MailWorkSheet()
'Only working in Excel 2016 for the Mac with Outlook 2016
Dim SourceWb As Workbook, DestWb As Workbook, sh As Worksheet
Dim strbody As String, TempFileName As String
Dim RunMyScript As String
'Exit the sub if it is Mac Excel 2011 or lower
If Val(Application.Version) < 15 Then Exit Sub
'Turn off Automatic Calculation
Application.Calculation = xlCalculationManual
'Turn off Alerts
Application.DisplayAlerts = False
'Check if the Script File is in the correct location
If CheckScript(ScriptFileName:="ExcelOutlook.scpt") = False Then
MsgBox "Sorry the ExcelOutlook.scpt file is not in the correct location, " & _
"Email File Manually."
Exit Sub
End If
With Application
'.ScreenUpdating = False
.EnableEvents = False
End With
'Set reference to the source workbook
Set SourceWb = ActiveWorkbook
'Create the body text in the strbody string
strbody = "<FONT size=""3"" face=""Calibri"">"
strbody = strbody & "Hello:" & "<br>" & "<br>" & _
"XXXXXXX" & "<br>" & _
" " & "<br>" & _
"XXXXXXX" & "<br>" & _
" " & "<br>" & _
"XXXXXXX"
strbody = strbody & "</FONT>"
'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy
Set DestWb = ActiveWorkbook
'Delete the button on the one sheet workbook
On Error Resume Next
DestWb.Sheets(1).DrawingObjects.Visible = True
DestWb.Sheets(1).DrawingObjects.Delete
On Error GoTo 0
'Enter the name of the file just created
TempFileName = "XXXXXXX" & " " _
& Range("A2") & " " & Format(Now, "mmm-dd-yy")
'Call the MailWithMac function to save the new file and create the mail
MailWithMac _
subject:="XXXXXXX", _
mailbody:=strbody, _
toaddress:=Range("A3"), _
ccaddress:="", _
bccaddress:="", _
displaymail:=True, _
accounttype:="", _
accountname:="", _
attachment:=TempFileName, _
FileFormat:=SourceWb.FileFormat
With Application
'.ScreenUpdating = True
.EnableEvents = True
End With
'Minimize Outlook
RunMyScript = AppleScriptTask("ExcelOutlook.scpt", "Mini", _
"/Library/Application Scripts/com.microsoft.Excel/ExcelOutlook.scpt")
'Turn on Automatic Calculation
Application.Calculation = xlCalculationAutomatic
'Turn Alert Messages On
Application.DisplayAlerts = True
End Sub
Function MailWithMac(subject As String, mailbody As String, _
toaddress As String, ccaddress As String, _
bccaddress As String, displaymail As Boolean, _
accounttype As String, accountname As String, _
attachment As String, FileFormat As Long)
'Function to create a mail with the activesheet
Dim FileExtStr As String, FileFormatNum As Long
Dim TempFilePath As String, fileattachment As String
Dim ScriptStr As String, RunMyScript As String
Select Case FileFormat
Case 52: FileExtStr = ".xlsx": FileFormatNum = 52
Case 53:
If ActiveWorkbook.HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 53
Else
FileExtStr = ".xlsx": FileFormatNum = 52
End If
Case 57: FileExtStr = ".xls": FileFormatNum = 57
Case Else: FileExtStr = ".xlsb": FileFormatNum = 51
End Select
'Save the new temporary workbook and close it
TempFilePath = _
MacScript("return POSIX path of (path to home folder) as string")
With ActiveWorkbook
.SaveAs TempFilePath & attachment & FileExtStr, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
'Build the AppleScriptTask parameter string
fileattachment = TempFilePath & attachment & FileExtStr
ScriptStr = subject & ";" & mailbody & ";" & toaddress & ";" & ccaddress & ";" & _
bccaddress & ";" & displaymail & ";" & accounttype & ";" & _
accountname & ";" & fileattachment
'Call the ExcelOutlook Script with the AppleScriptTask Function
RunMyScript = AppleScriptTask("ExcelOutlook.scpt", "CreateMailinOutlook", CStr(ScriptStr))
'Delete the file we just mailed
KillFile fileattachment
End Function
Function CheckScript(ScriptFileName As String) As Boolean
'Function to Check if the AppleScriptTask script file exists
Dim AppleScriptTaskFolder As String
Dim TestStr As String
AppleScriptTaskFolder = MacScript("return POSIX path of (path to desktop folder) as string")
AppleScriptTaskFolder = Replace(AppleScriptTaskFolder, "/Desktop", "") & _
"Library/Application Scripts/com.microsoft.Excel/"
On Error Resume Next
TestStr = Dir(AppleScriptTaskFolder & ScriptFileName, vbDirectory)
On Error GoTo 0
If TestStr = vbNullString Then
CheckScript = False
Else
CheckScript = True
End If
End Function
Function KillFile(Filestr As String)
'Function to Kill File
Dim ScriptToKillFile As String
Dim Fstr As String
'Delete files from a Mac using Applescript to avoid probelsm with long file names
If Val(Application.Version) < 15 Then
ScriptToKillFile = "tell applicatoin " & Chr(34) & _
"Finder" & Chr(34) & Chr(13)
ScriptToKillFile = ScriptToKillFile & _
"do shell script ""rm"" & quoted form of posix path of " & _
Chr(34) & Filestr & Chr(34) & Chr(13)
ScriptToKillFile = ScriptToKillFile & "end tell"
On Error Resume Next
MacScript (ScriptToKillFile)
On Error GoTo 0
Else
Fstr = MacScript("return POSIX path of (" & _
Chr(34) & Filestr & Chr(34) & ")")
On Error Resume Next
Kill Fstr
End If
End Function
Applescript:
on CreateMailInOutlook(paramString)
set {fieldValue1, fieldValue2, fieldValue3, fieldValue4, fieldValue5, fieldValue6, fieldValue7, fieldValue8, fieldValue9} to SplitString(paramString, ";")
tell application "Microsoft Outlook"
if fieldValue7 = "pop" then
set theAccount to the first pop account whose name is fieldValue8
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2, account:theAccount})
else if fieldValue7 = "imap" then
set theAccount to the first imap account whose name is fieldValue8
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2, account:theAccount})
else
set NewMail to (make new outgoing message with properties {subject:fieldValue1, content:fieldValue2})
end if
tell NewMail
repeat with toRecipient in my SplitString(fieldValue3, ",")
make new to recipient at end of to recipients with properties {email address:{address:contents of toRecipient}}
end repeat
repeat with toRecipient in my SplitString(fieldValue4, ",")
make new to recipient at end of cc recipients with properties {email address:{address:contents of toRecipient}}
end repeat
repeat with toRecipient in my SplitString(fieldValue5, ",")
make new to recipient at end of bcc recipients with properties {email address:{address:contents of toRecipient}}
end repeat
make new attachment with properties {file:POSIX file fieldValue9 as alias}
if fieldValue6 as boolean = true then
open NewMail
activate NewMail
else
send NewMail
end if
end tell
end tell
end CreateMailInOutlook
on SplitString(TheBigString, fieldSeparator)
tell AppleScript
set oldTID to text item delimiters
set text item delimiters to fieldSeparator
set theItems to text items of TheBigString
set text item delimiters to oldTID
end tell
return theItems
end SplitString
on Mini()
tell application "Microsoft Outlook"
tell (windows whose id is not (get id of front window) and visible is true)
set miniaturized to true
end tell
end tell
end Mini

Related

Combine code to attach pdf and screenshot

I have two pieces of code that work independently.
I would like to add a button to my sheet to do both. In other words to create the email with the screenshot generated by ScreenShotResults4() and attach the pdf generated by PrintPIP_To_PDF().
I tried combining but got syntax errors. I cobble code together with the help of sites like this.
Public Sub ScreenShotResults4()
Dim rng As Range
Dim olApp As Object
Dim Email As Object
Dim Sht As Excel.Worksheet
Dim wdDoc As Word.Document
Set rng = Sheets("Summary").Range("B21:N37")
rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set olApp = CreateObject("Outlook.Application")
Set Email = olApp.CreateItem(0)
Set wdDoc = Email.GetInspector.WordEditor
'strbody = "See production data for most recent 3 months. "
With Email
.To = Worksheets("Summary").Range("B21").Value
.Subject = "12 Month LO Production Lookback for " & Worksheets("Summary").Range("B21").Value & " (" & Worksheets("Summary").Range("B23").Value & "- " & Worksheets("Summary").Range("B35").Value & ")"
'.HTMLBody = "<BODY style=font-size:12.5pt;font-family:Calibri>" & "</p>" & strbody & RangetoHTML(rng) & Signature
.Display
wdDoc.Range.PasteAndFormat Type:=wdChartPicture
'if need setup inlineshapes hight & width
With wdDoc.Content
'--- paste the range image first, because it overwrites
' everything in the document
.PasteAndFormat Type:=wdChartPicture
'--- now add our greeting at the start of the email
.InsertBefore "See 12 month production data. " & vbCr & vbCr
'--- finally add our sign off after the image
.InsertAfter vbCr & _
"Thank you" & vbCr & vbCr
End With
.Display
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set Email = Nothing
Set olApp = Nothing
End Sub
Sub PrintPIP_To_PDF()
Application.EnableEvents = True
ActiveSheet.Unprotect Password:="Mortgage1"
Dim PrintRng As Range
Dim pdfile As String
'Setting range to be printed
Set PrintRng = Worksheets("PIP").Range("B3:M27")
'Range("B25:C25").Font.Color = RGB(255, 255, 255)
sPath = Environ("USERPROFILE") & "\Desktop\"
pdfile = Application.GetSaveAsFilename _
(InitialFileName:=sPath & "PIP" & " " & Worksheets("Summary").Range("B21").Value, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
Filename = pdfile
If Filename = False Then
Exit Sub
Else
PrintRng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Call MsgBox(pdfile & " file has been saved!")
ActiveSheet.Protect Password:="Mortgage1"
End If
End Sub
pls try this.
after displaying draft email .Display
use .Attachment.Add "C:\Test.pdf"
also if u wish to, u can save a copy of draft email (before sending) using
.SaveAs "C:\OutLookDrafts\Draft1.msg"

How to have Send To comprise of emails from worksheets that were proven true

I am trying to get my email lists from all worksheets that apply to the set rules to pull the email lists from said worksheet when appropriate. The column for mailing is S for every worksheet. I'm new to vba so I'm struggling a bit. This is the code I currently have. I guess I want the rules to kind of apply to the email list as well and pull from pages that have been proven true to generate the email in the first place. Thank you in advance for any help.
Option Explicit
Sub Main_AllWorksheets()
Dim sh As Worksheet, i As Long, shtsRotations As String
Dim shtsFunctions As String, shtsOK As String
Dim shtsManufacture As String
For Each sh In ActiveWorkbook.Worksheets
If Application.CountIf(sh.Range("O3:O70"), "<1") > 0 Then
shtsRotations = shtsRotations & vbLf & sh.Name
Else
shtsOK = shtsOK & vbLf & sh.Name & " (Rotations)"
End If
If Application.CountIf(sh.Range("P3:P70"), "<1") > 0 Then
shtsFunctions = shtsFunctions & vbLf & sh.Name
Else
shtsOK = shtsOK & vbLf & sh.Name & " (Functions)"
End If
If Application.CountIf(sh.Range("Q3:Q70"), "<1") > 0 Then
shtsManufacture = shtsManufacture & vbLf & sh.Name
Else
shtsOK = shtsOK & vbLf & sh.Name & " (Manufacturing Date)"
End If
Next sh
Dim myDataRng As Range
Set myDataRng = Range("S2:S15" & Cells(Rows.Count, "S").End(xlUp).Row)
Dim cell As Range
Dim iCnt As Integer
Dim sMail_ids As String
For Each cell In myDataRng
If Trim(sMail_ids) = "" Then
sMail_ids = cell.Offset(1, 0).Value
Else
sMail_ids = sMail_ids & vbCrLf & ";" & cell.Offset(1, 0).Value
End If
Next cell
Set myDataRng = Nothing ' Clear the range.
If Len(shtsRotations) > 0 Then
SendReminderMail sMail_ids, "Equipment rotations are due!", _
"Hello Team, " & vbNewLine & vbNewLine & _
"Check customer sheets: " & shtsRotations & vbLf & vbNewLine & _
"In the attatched workbook, you can see what equipment needs to be rotated by the red dates, indicating their last rotation."
End If
If Len(shtsFunctions) > 0 Then
SendReminderMail "sMail_ids", "Equipment functions are due! ", _
"Hello Team, " & vbNewLine & vbNewLine & _
"Check customer sheets: " & shtsFunctions & vbLf & vbNewLine & _
"In the attatched workbook, you can see what equipment needs to be functioned by the red dates, indicating their last function."
End If
If Len(shtsManufacture) > 0 Then
SendReminderMail "test#test.com", "Manufacturing date has surpassed 3 years!", _
"Hello Team, " & vbNewLine & vbNewLine & _
"Check customer sheets: " & shtsRotations & vbLf & vbNewLine & _
"In the attatched workbook, you can see what equipment has reached it's 3 years past manufacturing."
End If
If Len(shtsOK) > 0 Then
MsgBox "These sheets are OK: " & vbLf & shtsOK, vbInformation
End If
End Sub
Sub SendReminderMail(sTo As String, sSubject As String, sBody As String)
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim OutApp As Object
Dim OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wb1 = ActiveWorkbook
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb1.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb1.Name, Len(wb1.Name) - InStrRev(wb1.Name, ".", , 1)))
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
wb2.Worksheets(1).Range("A1").Value = "Copy created on " & Format(Date, "dd-mmm-yyyy")
wb2.Save
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = sTo
.CC = ""
.BCC = ""
.Subject = sSubject
.Body = sBody
.Attachments.Add wb2.FullName
.Display 'or use .Display
End With
On Error GoTo 0
wb2.Close savechanges:=False
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your Automated Email for the Workbook was successfully ran at " & TimeValue(Now), vbInformation
End Sub
Use the Recipients property of the MailItem class for specifying recipients. For example:
recipients = mail.Recipients
' now we add new recipietns to the e-mail
recipientTo = recipients.Add("Eugene Astafiev")
recipientTo.Type = Outlook.OlMailRecipientType.olTo
recipientCC = recipients.Add("Dmitry K.")
recipientCC.Type = Outlook.OlMailRecipientType.olCC
recipientBCC = recipients.Add("eugene.astafiev#somedomain.com")
recipientBCC.Type = Outlook.OlMailRecipientType.olBCC
retValue = recipients.ResolveAll()
Read more about that in the following articles:
How To: Fill TO,CC and BCC fields in Outlook programmatically
How To: Create and send an Outlook message programmatically

Excel VBA delete email after sending

might be you are able to help me with VBA code.
I got a code that send as PDF part of excel sheet.
Problem is that email is used by many people and sometimes text is confidential. Is there an option to delete email (sent items and deleted items) after email is sent?
Using office 2000
Here is my existing code.
Sub SendDDocs()
Dim IsCreated As Boolean
Dim PdfFile As String, Title As String
Dim OutlApp As Object
Dim rng As Range
Set rng = Range("A1:J103")
Title = Range("o1")
Title = Range("o1").Value & " Confidetial"
PdfFile = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & Title & ".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 = "email#email.com"
.CC = "email#email.com"
.Body = "" & vbLf & vbLf _
& "a" & vbLf & vbLf _
& "" & vbLf _
& Application.UserName & vbLf & vbLf
.Attachments.Add PdfFile
Application.Visible = True
.Display
End With
Kill PdfFile
If IsCreated Then OutlApp.Quit
Set OutlApp = Nothing
End Sub
Instead of .Display use
.DeleteAfterSubmit = True
.Send
to not save a copy in sent items.
See MailItem.DeleteAfterSubmit Property (Outlook).

Excel VBA - Send Email via CDO.message - cannot add attachment

I am following this tutorial to send emails via Gmail SMTP which is working well, but fails when it comes to adding an attachment.
http://www.learnexcelmacro.com/wp/2011/12/how-to-send-an-email-using-excel-macro-from-gmail-or-yahoo/
I am trying to send a copy of the active workbook which is saved into the users TEMP Appdata folder. I traced the temp file, checked for the files existence which is alright and should not be a problem, however, excel doesnt seem to attach it. I can however attach a file if I hardcode it (eg. "C:\temp\file.xls"), but not when the file path is given via variables.
Can anyone point me in the right direction please? I am out of ideas...
EDIT:
just to clarify, I tried several syntax's such as defining the path in the Gmail_Attachment variable or adding the TempFilePath & TempFileName & FileExtStr variables. None of them work, only if I literally code it as .addattachment "C:/path/file.xls" does it attach.
Sub Mail_Gmail()
'Working in 2000-2010
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb, Destwb As Workbook
Dim TempFilePath, TempFileName As String
Dim SendTo, SendCC, Holidex, Property, QCI_Mgr, Position As Range
Dim Gmail_ID, Gmail_PWD, Gmail_SMTP, Gmail_attachment As String
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
Set SendTo = ActiveWorkbook.Sheets("Settings").Range("B20")
Set SendCC = ActiveWorkbook.Sheets("Settings").Range("B21")
Set Holidex = ActiveWorkbook.Sheets("Settings").Range("B5")
Set Property = ActiveWorkbook.Sheets("Settings").Range("B4")
Set QCI_Mgr = ActiveWorkbook.Sheets("Settings").Range("B14")
Set Position = ActiveWorkbook.Sheets("Settings").Range("B15")
Gmail_SMTP = "smtp.gmail.com"
Gmail_ID = "user#gmail.com"
Gmail_PWD = "password"
'Copy the sheet to a new workbook
ActiveSheet.Copy Before:=Sheets(1)
With ActiveSheet
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
'.ShowAllData ' disable autofilters
.Cells.Copy
.Cells.PasteSpecial xlValues
End With
Application.CutCopyMode = False
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 2000-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2010, we exit the sub when your answer is
'NO in the security dialog that you only see when you copy
'an sheet from a xlsm file with macro's disabled.
If Sourcewb.Name = .Name Then
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your answer is NO in the security dialog"
Exit Sub
Else
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
'FileExtStr = ".pdf": FileFormatNum = 17
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End If
End With
'Change all cells in the worksheet to values if you want
'With Destwb.Sheets(1).Range("A1:I50")
' .Select
' .Copy
' .PasteSpecial xlPasteValues
'End With
'Application.CutCopyMode = False
'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "Part of " & Sourcewb.Name & " " _
& Format(Now, "dd-mmm-yy h-mm-ss")
Set NewMail = CreateObject("CDO.Message")
' Define Gmail configuration
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True ' Enalbe SSL
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 ' SMTP Authentication ON
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = Gmail_SMTP ' SMTP Server address
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 ' SMTP port
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 ' SMTP encryption
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = Gmail_ID ' Gmail ID
NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = Gmail_PWD ' Gmail PWD
NewMail.Configuration.Fields.Update ' Update all settings
With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, _
FileFormat:=FileFormatNum
.Close savechanges:=False
On Error Resume Next
Gmail_attachment = TempFilePath & TempFileName & FileExtStr
'Set All Email Properties
With NewMail
.From = Gmail_ID
.To = SendTo
.CC = SendCC
.BCC = ""
.Subject = Holidex & " System Login - " & ThisWorkbook.Name & " - " & Format(Now, "dd-mm-yyyy")
.textbody = "The following client has just logged in to this system:" & vbNewLine _
& "Date: " & Format(Now, "dd-mm-yyyy hh:ss") & vbNewLine _
& "System: F&B Feedback Card Summary" & vbNewLine _
& "Filename: " & ThisWorkbook.FullName
'.HTMLBody = "Write your complete HTML Page"
' For multiple Attachment you can add below lines as many times
.AddAttachment Gmail_attachment
End With
NewMail.Send ' or use .display
'MsgBox Gmail_attachment, vbOKOnly, "String"
End With
'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr
' Delete the duplicated worksheet and turn off prompts
Application.DisplayAlerts = False
With ActiveWorkbook
.ActiveSheet.Select
.ActiveSheet.Delete
.Sheets("Summary").Select
End With
Application.DisplayAlerts = True
' Clean up
Set NewMail = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
The problem is here in this section where one adds the .attachment "C:\file.xls" variable
'Set All Email Properties
With NewMail
.From = Gmail_ID
.To = SendTo
.CC = SendCC
.BCC = ""
.Subject = Holidex & " System Login - " & ThisWorkbook.Name & " - " & Format(Now, "dd-mm-yyyy")
.textbody = "The following client has just logged in to this system:" & vbNewLine _
& "Date: " & Format(Now, "dd-mm-yyyy hh:ss") & vbNewLine _
& "System: F&B Feedback Card Summary" & vbNewLine _
& "Filename: " & ThisWorkbook.FullName
'.HTMLBody = "Write your complete HTML Page"
' For multiple Attachment you can add below lines as many times
.AddAttachment Gmail_attachment
End With
The script does not support attaching open workbooks, hence I had to place .Close savechanges:=False right after the save dialog which solved the issue. Original post has been edited.

Trouble adding multiple images to an e-mail

I have an e-mail that is generated through Excel with VBA. This e-mail includes two embedded pictures in the body of the e-mail along with the separate hyperlinks to the videos they refer to. The problem is that it isn't recognizing the second picture and just embedding the same picture twice, however the hyperlinks are correct. Below is a sample of my code:
Private Sub SubmitBtn_Click()
Dim Source As Range
Dim Dest As Workbook
Dim wb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim OutApp As Object
Dim OutMail As Object
Dim MemNme As String, Email As String, UsrName As String, domainID As String, pic As String, pic2 As String
Dim Hlink As String, Hlink2 As String
State = Screener.StateBox
If State = "California" Then
If Screener.MktPlcBox = True Then
pic = "websitewithpicture1"
Hlink = "videolink"
count = 1
End If
If Screener.SubsidyBox = True Then
pic2 = "websitewithpicture2"
Hlink2 = "videolink"
count = 2
End If
With OutMail
.To = Email
.CC = ""
.BCC = ""
.Subject = "Helpful Video"
.HTMLBody = "Dear " & MemNme & ",<br><br>" _
& vbNewLine & vbNewLine & "Thank you for speaking with me today about your plan. You have a lot of choices, " _
& " and <b>we appreciate you choosing company</b>. Helping you understand your plan is important to us and I thought this video would be valuable to you.<br><br>" _
& vbNewLine & "<center><a href=" & Hlink & "<img src=cid:" & Replace(pic, " ", " ", "520") & " height =250 width=400></a>" _
& "<a href=" & Hlink2 & "<img src=cid:" & Replace(pic2, " ", " ", "420") & " height =250 width=400></a></center><br>" _
& vbNewLine & vbNewLine & "You can always get additional information at <b>website.com</b> or by calling the number on the back of your card.<br><br>" _
& vbNewLine & vbNewLine & "Thank you,<br>" _
& vbNewLine & UsrName
.Attachments.Add pic, olByValue, 0
.Attachments.Add pic2, olByValue, 0 <--------It doesn't "See" this pic???
' MsgBox "Press ok to create your e-mail"
.Display 'or use .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Unload Me
End Sub

Resources