Hi Iam using follwing code as a sample to send a mail with attachment via SMTP, but the attachment what it send is in XLSM format i need that to be in XLSX (non macro) format. Kindly help me to fo this.
Option Explicit
'This procedure will mail the whole workbook
'You can 't send a Workbook that is open with CDO.
'That's why it use SaveCopyAs to save it with another name and send that file.
Sub CDO_Mail_Workbook()
'Working in 2000-2007
Dim wb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim iMsg As Object
Dim iConf As Object
' Dim Flds As Variant
Set wb = ActiveWorkbook
If Val(Application.Version) >= 12 Then
If wb.FileFormat = 51 And wb.HasVBProject = True Then
MsgBox "There is VBA code in this xlsx file, there will be no VBA code in the file you send." & vbNewLine & _
"Save the file first as xlsm and then try the macro again.", vbInformation
Exit Sub
End If
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Make a copy of the file/Mail it/Delete it
'If you want to change the file name then change only TempFileName
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb.Name, Len(wb.Name) - InStrRev(wb.Name, ".", , 1)))
wb.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
' iConf.Load -1 ' CDO Source Defaults
' Set Flds = iConf.Fields
' With Flds
' .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "Fill in your SMTP server here"
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
' .Update
' End With
With iMsg
Set .Configuration = iConf
.To = "ron#debruin.nl"
.CC = ""
.BCC = ""
.From = """Ron"" <ron#something.nl>"
.Subject = "This is a test"
.TextBody = "This is the body text"
.AddAttachment TempFilePath & TempFileName & FileExtStr
.Send
End With
'If you not want to delete the file you send delete this line
Kill TempFilePath & TempFileName & FileExtStr
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
I think what you'll need to do, is have this code reside in an add-in. That way you aren't trying to send the existing file with code via email.
You are sending workbook which you are running code from so it must be .xlsm and so you send it.
You must either create a copy of your workbook without macros and then send this copy or move your macro to PERSONAL (assuming macro you posted is the only code contained in your workbook)
Related
This question already has answers here:
How to add an attachment to an email using VBA in Excel
(2 answers)
Closed 1 year ago.
I am working on an userform in VBA Excel that allows a user to submit their request. The users complete the form then click on the Send button. An Outlook mail will be opened and the completed form is automatically attached.
The users usually have data or/and documents related to the request. I want to add functionality to my userform, which allows them to browse their PC and import the files. When they click on the Send button, these files will be attached to the same mail as the original Excel form.
Below are the codes for my Send button.
Function CreationMail(criticité As String)
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim rng As Range
Set Sheet1 = ThisWorkbook.Sheets("Formulaire")
Set rng = Sheets("Formulaire").Range("C6:D11").SpecialCells(xlCellTypeVisible)
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
End If
Case Excel8:
xFile = ".xls"
xFormat = Excel8
Case xlExcel12:
xFile = ".xlsb"
xFormat = xlExcel12
End Select
FilePath = Environ$("temp") & "\"
FileName = "STATSAE" & "_" & Format(Now, "yymmdd") & "_" & Format(Now, "hhnnss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.To = ";" & ";"
.CC = ""
If criticité = "Haute" Then
.Importance = olImportanceHigh
End If
If criticité = "" Then
.Importance = olImportanceNormal
End If
If criticité = "Faible" Then
.Importance = olImportanceNormal
End If
.Subject = "Request" & Space(1) & FileName
.Attachments.Add Wb2.FullName
.Body = "Please find the requested information" & vbCrLf & "Best Regards"
.HTMLBody = RangetoHTML(rng)
.Display
End With
Wb2.Close
Kill FilePath & FileName & xFile
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
End Function
First of all, you need to do customizations to your form to pick up files that requires to be attached to the email. Then in the code you can repeat the Add method of the Attachments class for each entry the user has chosen. The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
.Attachments.Add Wb2.FullName
.Attachments.Add your_chosen_file
I am working to get the code below to work so when I click a button the workbook will save a temporary copy of the workbook, open a new email in outlook, then attach the temp copy to the email to be sent. Everytime it gets to the 'Break External Links section it throws a run time 91. I have worked on this for hours and I know it is mostlikely simple but I am currently at a loss. Any help is greatly appreciated.
Sub EmailWorkbook()
'PURPOSE: Create email message with ActiveWorkbook attached
Dim SourceWB As Workbook
Dim DestinWB As Workbook
Dim OutlookApp As Object
Dim OutlookMessage As Object
Dim TempFileName As Variant
Dim ExternalLinks As Variant
Dim TempFilePath As String
Dim FileExtStr As String
Dim DefaultName As String
Dim UserAnswer As Long
Dim x As Long
Set SourceWB = ActiveWorkbook
'Check for macro code residing in
If Val(Application.Version) >= 12 Then
If SourceWB.FileFormat = 51 And SourceWB.HasVBProject = True Then
UserAnswer = MsgBox("There was VBA code found in this xlsx file. " & _
"If you proceed the VBA code will not be included in your email attachment. " & _
"Do you wish to proceed?", vbYesNo, "VBA Code Found!")
If UserAnswer = vbNo Then Exit Sub 'Handle if user cancels
End If
End If
'Determine Temporary File Path
TempFilePath = Environ$("temp") & "\"
'Determine Default File Name for InputBox
If SourceWB.Saved Then
DefaultName = Left(SourceWB.Name, InStrRev(SourceWB.Name, ".") - 1)
Else
DefaultName = SourceWB.Name
End If
'Ask user for a file name
TempFileName = Application.InputBox("What would you like to name your attachment? (No Special Characters!)", _
"File Name", Type:=2, Default:=DefaultName)
If TempFileName = False Then Exit Sub 'Handle if user cancels
'Determine File Extension
If SourceWB.Saved = True Then
FileExtStr = "." & LCase(Right(SourceWB.Name, Len(SourceWB.Name) - InStrRev(SourceWB.Name, ".", , 1)))
Else
FileExtStr = ".xlsm"
End If
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
'Save Temporary Workbook
SourceWB.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set DestinWB = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
'Break External Links
ExternalLinks = DestinWB.LinkSources(Type:=xlLinkTypeExcelLinks)
'Loop Through each External Link in ActiveWorkbook and Break it
On Error Resume Next
For x = 1 To UBound(ExternalLinks)
DestinWB.BreakLink Name:=ExternalLinks(x), Type:=xlLinkTypeExcelLinks
Next x
On Error GoTo 0
'Save Changes
DestinWB.Save
'Create Instance of Outlook
On Error Resume Next
Set OutlookApp = GetObject(class:="Outlook.Application") 'Handles if Outlook is already open
Err.Clear
If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(class:="Outlook.Application") 'If not, open Outlook
If Err.Number = 429 Then
MsgBox "Outlook could not be found, aborting.", 16, "Outlook Not Found"
GoTo ExitSub
End If
On Error GoTo 0
'Create a new email message
Set OutlookMessage = OutlookApp.CreateItem(0)
'Create Outlook email with attachment
On Error Resume Next
With OutlookMessage
.Display
.To = ""
.CC = ""
.BCC = ""
.Subject = "RealPage Implementation Template Workbook."
.HTMLBody = "Thank you for your time. The attached file are the templates that we covered during our call." & "<br>" & .HTMLBody
.Attachments.Add DestinWB.FullName
End With
On Error GoTo 0
'Close & Delete the temporary file
DestinWB.Close SaveChanges:=False
Kill TempFilePath & TempFileName & FileExtStr
'Clear Memory
Set OutlookMessage = Nothing
Set OutlookApp = Nothing
'Optimize Code
ExitSub:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
I am using a below code that is pasting a table from excel to the outlook file. However, right now the table is pasted on the very bottom of the email - after the signature.
What I would like to achieve is to have the table inserted after a word "region." and before "Regards" - so before signature.
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Dim DateString As String
Dim FolderName As String
Dim myOutlook As Object
Dim myMailItem As Object
Dim mySubject As String
Dim myPath As String
Dim i As Integer
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'Prompt for Email Subject
Set outlApp = CreateObject("Outlook.Application")
weeknumber = "Week " & WorksheetFunction.WeekNum(Now, vbMonday)
'mySubject = InputBox("Subject for Email")
For i = 2 To 3
region = Sheets("Sheet1").Cells(i, 5).Value
mySubject = "Overdue Milestones | " & weeknumber & " | " & region
'Copy every sheet from the workbook with this macro
Set Sourcewb = ActiveWorkbook
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = "C:\Users\mxr0520\Desktop\Ignite Reports\Milestones\" & weeknumber
If i < 3 Then
MkDir FolderName
Else
End If
'Copy every visible sheet to a new workbook
Set sh = Sheets(region)
'If the sheet is visible then copy it to a new workbook
If sh.Visible = -1 Then
sh.Copy
'Set Destwb to the new workbook
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
If Sourcewb.Name = .Name Then
MsgBox "Your answer is NO in the security dialog"
GoTo GoToNextSheet
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
End With
'Change all cells in the worksheet to values if you want
If Destwb.Sheets(1).ProtectContents = False Then
With Destwb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
End If
'Save the new workbook, email it, and close it
'Set otlNewMail = outlApp.CreateItem(myMailItem)
Set OutLookApp = CreateObject("Outlook.application")
Set OutlookMailitem = OutLookApp.CreateItem(0)
With OutlookMailitem
.display
End With
Signature = OutlookMailitem.htmlbody
With Destwb
.SaveAs FolderName _
& "\" & Destwb.Sheets(1).Name & FileExtStr, _
FileFormat:=FileFormatNum
End With
myPath = ActiveWorkbook.path & "\" & ActiveWorkbook.Name
With Destwb
.Close False
End With
With OutlookMailitem
.Subject = mySubject
.To = Sheets("Sheet1").Cells(i, 6)
.CC = Sheets("Sheet1").Cells(i, 7)
.htmlbody = "Dear All," & "<br>" _
& "<br>" _
& "Attached please find the list of milestones that are <b>overdue</b> and <b>due in 14 days</b> for " & region & "." & "<br>" & "<br>" & "Regards," & "<br>" _
& "Marek" _
& Signature
.Attachments.Add myPath
Worksheets("Summary").Range("A1:E14").Copy
Set vInspector = OutlookMailitem.GetInspector
Set weditor = vInspector.WordEditor
wEditor.Application.Selection.Start = Len(.body)
wEditor.Application.Selection.End = wEditor.Application.Selection.Start
wEditor.Application.Selection.Paste
.display
End With
Set OutlookMailitem = Nothing
End If
thank you for help in advance!
Probably easiest to do this by creating an .oft (Outlook Email Template) with the message body and a placeholder for "region" and the table. Create the template without a signature, it will be added automatically per your Outlook user settings, later. I create a template like this, and save as .oft:
Then simply create the new mailitem with Set OutlookMailitem = OutlookApp.CreateItemFromTemplate({path to your template.oft}), replace the "region" placeholder, and copy/paste the table to the table placeholder's location.
Option Explicit
Sub foo()
Dim objOutlook As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim wdDoc As Word.Document
Dim tblRange As Word.Range
Dim region As String
' define your Region, probably this is done in a loop...
region = "Region 1"
Set objOutlook = CreateObject("Outlook.Application")
' Create email from the template file // UPDATE WITH YOUR TEMPLATE PATH
Set objMsg = objOutlook.CreateItemFromTemplate("C:\path\to\your\template.oft")
objMsg.Display
Set wdDoc = objOutlook.ActiveInspector.WordEditor
' replace placeholder with region:
wdDoc.Range.Find.Execute "{{REGION PLACEHOLDER}}", ReplaceWith:=region
' in my template, paragraph 5 is the table placeholder, modify as needed:
Set tblRange = wdDoc.Range.Paragraphs(5).Range
tblRange.Text = "" ' remove the placeholder text
' copy the Excel table // modify to refer to your correct table/range
Sheet1.ListObjects(1).Range.Copy
' paste the table into the email
tblRange.PasteExcelTable False, False, False
End Sub
As you can see, the final email contains my default signature (which was not part of the template.oft file).
You can use the following properties to customize the message body:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
The Word Editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. You can find all these ways described in the Chapter 17: Working with Item Bodies in MSDN.
The Outlook object model doesn't provide any property or method for detecting signatures. You parse the message body and try to find such places.
However, when you create a signature in Outlook, three files (HTM, TXT and RTF) are created in the following folders:
Vista and Windows 7/8/10:
C:\Users\<UserName>\AppData\Roaming\Microsoft\Signatures
Windows XP:
C:\Documents and Settings\<UserName>\Application Data\Microsoft\Signatures
Application Data and AppData are hidden folders, change the view in the Windows explorer so it shows hidden files and folders if you want to see the files.
So, you read the content of these files and try to find the corresponding content in the message body. Note, users may type a custom signature in the end of emails.
I am making a macro to take my originfile, SaveAsCopy tempfile, delete some sheets and some columns from tempfile and finally send tempfile by Outlook mail.
My code compiles and runs. It does not work great. It doesn't do any modification: so the deleting stuff in the newly generated tempfile is missing.
This is my code :
Macro Master
Sub run_all()
Call files_mang
Call delete
Call mailing_tempfile
End Sub
Sub files_mang()
' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010,
' Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, Outlook 2010.
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim OrigFileName As String
Dim FileExtStr As String
TempFilePath = "filepathhere"
FileExtStr = ".xlsx"
OrigFileName = TempFilePath & "Suivi interne déploiements OINIS S40" & FileExtStr
TempFileName = "Suivi déploiements OINIS - NOKIA S40" & FileExtStr
Set wb1 = Workbooks.Open(OrigFileName)
Set wb1 = ActiveWorkbook
If Val(Application.Version) >= 12 Then
If wb1.FileFormat = 51 And wb1.HasVBProject = True Then
MsgBox "There is VBA code in this xlsx file. There will" & vbNewLine & _
"be no VBA code in the file you send. Save the" & vbNewLine & _
"file as a macro-enabled (. Xlsm) and then retry the macro.", vbInformation
Exit Sub
End If
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Make a copy of the file.
' If you want to change the file name then change only TempFileName variable.
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
Set wb2 = ActiveWorkbook
End Sub
Sub delete()
Application.DisplayAlerts = False
'Delete columns like intern com ect ...
With Worksheets("Suivi Projet WELDON")
.Columns("R:X").delete
End With
With Worksheets("Suivi projet Highway")
.Columns("T:Z").delete
End With
'Delete non usful sheets for client
Worksheets("SuiviCarteOrange").delete
Worksheets("Cartes Orange En Panne").delete
Application.DisplayAlerts = True
End Sub
Sub mailing_tempfile()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
' Change the mail address and subject in the macro before you run this procedure.
With OutMail
.To = "emailaddresshere"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hello World!"
.Attachments.Add ActiveWorkbook.FullName
' You can add other files by uncommenting the following line.
'.Attachments.Add ("C:\test.txt")
' In place of the following statement, you can use ".Display" to
' display the mail.
.Send
End With
On Error GoTo 0
ActiveWorkbook.Close SaveChanges:=False
' Delete the file.
'Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
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.