code to be added in existing vba to attach an excel file in emails

aravindhan_31

Well-known Member
Joined
Apr 11, 2006
Messages
672
Office Version
  1. 365
  2. 2019
  3. 2016
Platform
  1. Windows
I have posted this question in
http://www.excelforum.com/excel-programming/639572-excel-macro-for-sending-emails-2.html#post1959252

Hi,

I have the following code to send automatic email to n number of people at one short.

I have 3 columns in excel.
Column A - Email addres
Column B - Some numbers ( subject)
Column C - Some Links ( body of the message)

wen i run the macro, email goes to all the email address in column A with the subject in column B and with the links in column c respectively and adds the body of the message in sheet 2.

the program is working fine. I just want to add the code to attach an excel file to all these emails.
Assume I have the excel file in My C drive my documents folder.

The code is below


Thanks to leith for providing this code earlier.

'Written: March 31, 2008
'Author: Leith Ross
'Summary: Sends out emails from a worksheet list. The message body is on
' a separate worksheet. This worksheet is copied to a file in
' HTML format. The file is opened an copied as a string which
' becomes the mesaage body in Outlook.

'Used to find the Outlook icon in the system tray. If present then Outlook is running
Private Declare Function FindWindow _
Lib "user32.dll" _
Alias "FindWindowA" _
(ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long

Sub EmailFromWorksheet()

Dim FSO As Object
Dim HTMLcode As String
Dim HTMLfile As Object
Dim Msg As String
Dim myInstance As Boolean
Dim olApp As Object
Dim olEmail As Object
Dim olPID As Long
Dim R As Long
Dim TempFile As String
Dim Wks As Worksheet

'Outlook constants aren't available using late binding
Const olByValue = 1
Const olCC = 2
Const olFolderContacts = 10
Const olMailItem = 0
Const olFormatHTML = 2

'Starting Row of Email Data
R = 2

'Set some program variables
TempFile = "C:\MyEmail.htm"
Set Wks = Worksheets("Body of the Message")

'Start Outlook if it isn't running
If FindWindow("Outlook Notification Area Icon Window", vbNullString) = 0 Then
myInstance = True
olPID = Shell("C:\Program Files\Microsoft Office\Office11\OUTLOOK.exe", 2)
End If

'Assign variable to the running instance
Set olApp = GetObject("", "Outlook.Application")

'Trap any errors
On Error GoTo CleanUp

'Stop the email loop if cell is blank
Do While Cells(R, "A") <> ""

'Add URL to the Body of the Message worksheet
Wks.Cells(1, "A") = Cells(R, "C").Text

'Convert the Message worksheet into HTML
With ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
FileName:=TempFile, _
Sheet:=Wks.Name, _
Source:=Wks.UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With

'Read the HTML file back as a string
Set FSO = CreateObject("Scripting.FileSystemObject")
Set HTMLfile = FSO.GetFile(TempFile).OpenAsTextStream(1, -2)
HTMLcode = HTMLfile.ReadAll
HTMLfile.Close
HTMLcode = Replace(HTMLcode, "align=center x:publishsource=", _
"align=left x:publishsource=")

'Compose the email
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
.To = Cells(R, "A").Text
.Subject = Cells(R, "B").Text 'Voucher Number
.BodyFormat = olFormatHTML
.HTMLBody = HTMLcode
.Send
End With

'Increment Row counter
R = R + 1
'Delete the tempoary file
Kill TempFile
'Delete the Published Object
With ActiveWorkbook.PublishObjects
.Item(.Count).Delete
End With
'Get the next email cell
Loop

CleanUp:
'Close Outlook instance if this macro created it
If myInstance = True Then TerminateProcess olPID
'Was there an error
If Err <> 0 Then
'Delete the Temp File
If Dir(TempFile) <> "" Then Kill TempFile
'Delete the Publish Object
With ActiveWorkbook.PublishObjects
If .Count <> 0 Then .Item(.Count).Delete
End With
End If

'Free memory resources
Set olApp = Nothing
Set olEmail = Nothing
Set FSO = Nothing

End Sub

Public Sub TerminateProcess(ByVal PID As Long)

Dim colProcessList As Object
Dim objProcess As Object
Dim objServices As Object
Dim ProcessRetVal As Long

'Connect to the WMI namespace through the local computer "."
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objServices = objLocator.ConnectServer(".", "root\cimv2")

' Terminate the Application by its Process ID
Set colProcessList = objServices.ExecQuery _
("SELECT * FROM Win32_Process WHERE ProcessId =" & Str(PID))

' WMI requires a loop even if there is only one object
For Each objProcess In colProcessList
ProcessRetVal = objProcess.Terminate()
If ProcessError(ProcessRetVal) Then Exit For
Next objProcess

CleanUp:
Set objLocator = Nothing
Set objServices = Nothing
Set colProcessList = Nothing
Set objProcess = Nothing
End Sub

Private Function ProcessError(ByVal Err_Value As Long) As Boolean
Dim Msg As String
If Err_Value = 0 Then Exit Function

ProcessError:
Select Case Err_Value
Case 2
Msg = "Access Denied"
Case 3
Msg = "Insufficient Privilege"
Case 8
Msg = "Unknown failure"
Case 9
Msg = "Path Not Found"
Case 21
Msg = "Invalid Parameter"
End Select
MsgBox Msg, vbexcalamtion, "WMI Win32_Process"
ProcessError = True
End Function
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
NOt tested, but try this amendment

Code:
'Compose the email
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
    .To = Cells(R, "A").Text
    .Subject = Cells(R, "B").Text 'Voucher Number
    .Attachments.Add ("filename")
    .BodyFormat = olFormatHTML
    .HTMLBody = HTMLcode
    .Send
End With
 
Upvote 0
Hi,

Thanks for your reply, but it is not working, the macro stops working If I add this line in the code : .Attachments.Add ("filename")

Regards
Arvind..
 
Upvote 0
I don't think I should have added the brackets, they seem superfluous, but what do you mean by the macro stgops working?
 
Upvote 0
Hi,

This is the code I replace

'Compose the email
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
.To = Cells(R, "A").Text
.Subject = Cells(R, "B").Text 'Voucher Number
.Attachment.Add "New Microsoft Excel Worksheet"
.BodyFormat = olFormatHTML
.HTMLBody = HTMLcode
.Send
End With


the macro stops working- I mean, if i dont add this line and run the macro an automated emails are going to and I can see them on sent itesm in outlook.

But if I add that line, and the run the macro nothing happens. I dont even get an error message and no email is going..

And i tried adding brackets also Attachment.Add ("New Microsoft Excel Worksheet")[/B] , but same problem

Thanks...
 
Upvote 0
You have to include the path and the file extension of the Excel file, it is getting it from the HDD not from memory.
 
Upvote 0
Hi,

I tried with that optionm as well, but i still have a problem,

'Compose the email
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
.To = Cells(R, "A").Text
.Subject = Cells(R, "B").Text 'Voucher Number
.Attachment.Add ("C:\Documents and Settings\dilip\Desktop\Test file.xls")
.BodyFormat = olFormatHTML
.HTMLBody = HTMLcode
.Send
End With

I dont know where I am going wrong...
 
Upvote 0
Hi

Thanks a lot....

Its working.. I missed s in Attachment. thz y it was not working...
should be .Attachments.Add I typed Attachment.Add.

Thanks a lot
 
Upvote 0

Forum statistics

Threads
1,215,950
Messages
6,127,906
Members
449,411
Latest member
AppellatePerson

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