Sending multiple attachments from excel sheet with VBA - vba

I have the existing code to send a mail from a Sheet in my Excel file -
Sub CreateMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Dim rngAttach As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
Application.ScreenUpdating = False
Worksheets("Mail List").Activate
With ActiveSheet
Set rngTo = .Range("B1")
Set rngSubject = .Range("B2")
Set rngBody = .Range("B3")
Set rngAttach = .Range("B4")
End With
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.body = rngBody.Value
.Attachments.Add rngAttach.Value
.display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
End Sub
However, I want to include a number of attachments, and hence the
Set rngAttach = .Range("B4") does not help to do this.
Any help on this?
Thanks in advance!

Enclose your .Attachments.Add statement in loop. Something like below might work
For i = 4 To 6
.Attachments.Add Range("B" & i).Value
Next i

To make it Dynamic you can set the upper limit of i to the last row in Column B
For i = 4 To Range("B" & rows.count).end(xlUp).row
.Attachments.Add Range("B" & i).Value
Next i

This updated code:
Looks for file names from B4
Uses Dir to ensure the attached files actually exist at the specified path
Tidies up the worksheet code (Activate is unnecessary)
Sub CreateMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Dim rngAttach As Range
Dim rng2 As Range
Dim ws As Worksheet
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
Application.ScreenUpdating = False
Set ws = Worksheets("Mail List")
With ws
Set rngTo = .Range("B1")
Set rngSubject = .Range("B2")
Set rngBody = .Range("B3")
Set rngAttach = ws.Range(ws.[b4], ws.Cells(Rows.Count, "B").End(xlUp))
End With
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.body = rngBody.Value
For Each rng1 In rngAttach.Cells
If Len(Dir(rng1)) > 0 Then .Attachments.Add rng1.Value
Next
.display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
End Sub

Related

Attach a PPT in outlook through VBA [duplicate]

I have the following code but it is not working. I am fairly new to VBA as well. The code works to populate the email template but as soon as I add the .Attachment.Add it does not work.
Sub CreateMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With ActiveSheet
Set rngTo = .Range("E2")
Set rngSubject = .Range("E3")
Set rngBody = .Range("E4")
.Attachments.Add "Z:\PHS 340B\Letters of Non-Compliance\..Resources\W9 Form\VPNA W-9 01 09 2017"
End With
With objMail
.to = rngTo.Value
.Subject = rngSubject.Value
.Body = rngBody.Value
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
End Sub
Try this:
Sub emailtest()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With ActiveSheet
Set rngTo = .Range("E2")
Set rngSubject = .Range("E3")
Set rngBody = .Range("E4")
End With
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.Body = rngBody.Value
.Attachments.Add "Z:\PHS 340B\Letters of Non-Compliance\..Resources\W9 Form\VPNA W-9 01 09 2017"
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
End Sub
You need to use the .Attachments.Add when working within Outlook not Excel.
This simple script should illustrate the point of how to add attachments to an email, and then send the email.
Sub Mail_workbook_Outlook_1()
'Working in Excel 2000-2016
'This example send the last saved version of the Activeworkbook
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hi there"
.Attachments.Add ActiveWorkbook.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
https://www.rondebruin.nl/win/s1/outlook/amail1.htm

Add Range along with text in outlook

Below coding is working fine to send an email with the excel range. Just wanted to all "Hello**" at the top of the email Body (Left alignment). Please assist.
Dim OutApp As Object, OutMail As Object
Dim wdDoc As Object, wdRange As Object
Dim rng As Range
Dim i As Long
Set rng = ThisWorkbook.Sheets("Certificate").Range("A1:O36")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ""
.BCC = ""
.Subject = "Subject"
.Display
Set wdDoc = .GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
rng.Copy
wdRange.Paste
DoEvents
Set wdRange = wdDoc.Range(0, wdDoc.Characters.Count)
'wdRange.ParagraphFormat.Alignment = wdAlignParagraphCenter
For i = 1 To wdRange.Tables.Count
wdRange.Tables(i).Rows.Alignment = wdAlignRowCenter
Next i
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Try the next way, please:
Sub sendOutlookMail()
Dim OutApp As Object, OutMail As Object
Dim wdDoc As Object, wdRange As Object
Dim rng As Range, i As Long
Set rng = ThisWorkbook.Sheets("Certificate").Range("A1:O36")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ""
.BCC = ""
.subject = "Subject"
.display
Set wdDoc = .GetInspector.WordEditor
With wdDoc
.Paragraphs(1).Range.InsertAfter ("Hello!" & vbCrLf)
rng.Copy
.Paragraphs(2).Range.Paste
End With
End With
End Sub

Sending Multiple mails using excel cell values using VP

I have an old script to send multiple mails from excel using Cell values, 1st cell is the E-Mail address, 2nd is Mail Subject, 3rd contains the mail body, it doesn't work anymore!! HELP PLZ
Sub CreateMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngEntry As Range
Dim rngEntries As Range
Set objOutlook = CreateObject("Outlook.Application")
Set rngEntries = ActiveSheet.Range("B:B")
For Each rngEntry In rngEntries
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = rngEntry.Value
.Subject = rngEntry.Offset(0, 1).Value
.Body = rngEntry.Offset(0, 2).Value
'.Attachments.Add rngEntry.Offset(0, 3).Value
.Send '.Display or .Save
End With
Next rngEntry
Set objOutlook = Nothing
Set objMail = Nothing
Set rngEntry = Nothing
Set rngEntries = Nothing
End Sub
Your vba code does send emails to any names in column B. However, when it hits the first row with no data it attempts to send an email without a "To:" party. This fix will stop the subroutine when it hits an empty cell in column B:
Sub CreateMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngEntry As Range
Dim rngEntries As Range
Set objOutlook = CreateObject("Outlook.Application")
Set rngEntries = ActiveSheet.Range("B:B")
For Each rngEntry In rngEntries
If rngEntry.Value <> "" Then ' ADD THIS LINE HERE
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = rngEntry.Value
.Subject = rngEntry.Offset(0, 1).Value
.Body = rngEntry.Offset(0, 2).Value
'.Attachments.Add rngEntry.Offset(0, 3).Value
.Send '.Display or .Save
End With
Else ' ADD THIS LINE HERE
Exit Sub ' ADD THIS LINE HERE
End If ' ADD THIS LINE HERE
Next rngEntry
Set objOutlook = Nothing
Set objMail = Nothing
Set rngEntry = Nothing
Set rngEntries = Nothing
End Sub

Runtime Error 424: Object not Defined"- While Sending Email Using Outlook 2013

I am using below code to send multiple emails through outlook, this code is working fine when I use Excel 2007 and Outlook 2007 however when I tried to run same code in Excel 2013 and Outlook 2013 it is throwing an error "Runtime Error 424: Object not Defined" in the below code:
Set Doc = olMail.GetInspector.WordEditor
Can somebody please check below coding and let me know what do I need to change if I want to use same macro in 2013 version?
Sub Msmail()
Dim otlApp As Object
Dim olMail As Object
Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook
Worksheets("Mail").Select
ActiveSheet.Calculate
Total_Site = Range("Total_Site")
For Site_Count = 1 To Total_Site
Application.StatusBar = False
ActiveSheet.Calculate
Range("Site_Count") = Site_Count
ActiveSheet.Calculate
If Range("Send_Email") = "Y" Then
Set mainWB = ActiveWorkbook
Set olMail = otlApp.CreateItem(olMailItem)
Set Doc = olMail.GetInspector.WordEditor '<~ ERROR 424 HERE
SendID = mainWB.Sheets("Mail").Range("To_List").Value
CCID = mainWB.Sheets("Mail").Range("Cc_List").Value
Subject = mainWB.Sheets("Mail").Range("Subject_Line").Value
Body = mainWB.Sheets("Summary").Range("Mail_Body").Value
AttachFile = mainWB.Sheets("Mail").Range("StrPath").Value
StrPath = ActiveSheet.Range("StrPath").Value
With olMail
.To = SendID
If CCID <> 0 Then
.CC = CCID
End If
.Subject = Subject
mainWB.Sheets("Summary").Range("Mail_Body").Copy
Set WrdRng = Doc.Range
.Display
WrdRng.Paste
'StrPath = Range("StrPath").Value
StrFile = Range("StrFile").Value & "*.*"
StrFile = Range("StrFile").Value
.Attachments.Add StrPath & "\" & StrFile
.Send
End With
End If
Next Site_Count
End Sub
OK - so there appear to be quite a lot of issues with the current code; you have duplication of code and non-dimensioned variables. I have tried to condense the code down, added direct references and this will hopefully make it more readable and (should maybe) work, but it's untested... I don't have the ranges set out in relevant sheets and no data to test it
Sub msMail()
Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim olMail As Object
Dim Total_Site As Range, Doc As Variant, WrdRng As Range
Dim StrPath As String, StrFile As String, Site_Count As Long
Dim wbMain As Workbook: Set wbMain = ThisWorkbook
Dim wsMail As Worksheet: Set wsMail = wbMain.Worksheets("Mail")
Dim wsSumm As Worksheet: Set wsSumm = wbMain.Worksheets("Summary")
With wsMail
.Calculate ' Not sure why this is included...
Set Total_Site = Range("Total_Site")
For Site_Count = 1 To Total_Site.Count
''Application.StatusBar = False
Range("Site_Count") = Site_Count
If Range("Send_Email") = "Y" Then
Set olMail = olApp.CreateItem(olMailItem)
Set Doc = olMail.GetInspector.WordEditor
If Not Doc Is Nothing Then
With olMail
.To = wsMail.Range("To_List")
.CC = IIf(wsMail.Range("Cc_List") <> 0, wsMail.Range("Cc_List"), "")
.Subject = wsMail.Range("Subject_Line")
wsSumm.Range("Mail_Body").Copy
Set WrdRng = Doc.Range
.Display
WrdRng.Paste
StrPath = wsMail.Range("StrPath")
StrFile = wsMail.Range("StrFile")
.Attachments.Add StrPath & "\" & StrFile
' .Send
End With
End If
End If
Next Site_Count
End With
End Sub

Capture current time in next empty cell

If I click on a button the time should be captured in Column E in the first empty cell starting at cell E5 and if that cell is not empty then it should automatically go to the next cell E6 then E7 ...
Here is the code that I use currently, but it doesn't work:
Sub Button4_Click()
ActiveSheet.Unprotect "pramtesh"
ActiveWorkbook.Unprotect "pramtesh"
ActiveSheet.Value = Time()
ActiveSheet.Protect "pramtesh"
ActiveWorkbook.Protect "pramtesh"
Dim olApp As Object
Dim olMailItm As Object
Dim iCounter As Integer
Dim Dest As Variant
Dim SDest As String
Set olApp = CreateObject("Outlook.Application")
Set olMailItm = olApp.CreateItem(0)
With olMailItm
.To = ""
.CC = ""
.Subject = ""
.Body = ""
.Display
Application.Wait (Now)
Application.SendKeys "%s"
End With
Set olMailItm = Nothing
Set olApp = Nothing
End Sub
There is no need to use the SendKeys method for sending an email programmatically. Instead, I'd suggest using the Send method of the MailItem class. See the Using Automation to Send a Microsoft Outlook Message article for a sample code.
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Add the CC recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Michael Suyama")
objOutlookRecip.Type = olCC
' Add the BCC recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("Andrew Fuller")
objOutlookRecip.Type = olBCC
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
' Add attachments to the message.
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
' Resolve each Recipient's name.
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
' Should we display the message before sending?
If DisplayMsg Then
.Display
Else
.Save
.Send
End If
End With
Set objOutlook = Nothing
End Sub
Also you can read more about that in the How to automate Outlook from another program article.
use this
Sub Button4_Click()
Dim iCounter%, Dest As Variant, SDest$, Lrow&
Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim olMailItm As Object: Set olMailItm = olApp.CreateItem(0)
'determinate the last used cell in column "E"
Lrow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row
'additional verification
If Lrow < 5 Then 'if last used cell before [E5] then will be used [E5]
Lrow = 5
Else 'otherwise move to the next cell after last filled cell
Lrow = Lrow + 1
End If
ActiveSheet.Unprotect "pramtesh": ActiveWorkbook.Unprotect "pramtesh"
ActiveSheet.Cells(Lrow, "E").Value = Time() 'insert time into the cell
ActiveSheet.Protect "pramtesh": ActiveWorkbook.Protect "pramtesh"
With olMailItm
.To = ""
.CC = ""
.Subject = ""
.Body = ""
.Display
Application.Wait (Now)
Application.SendKeys "%s"
End With
Set olMailItm = Nothing: Set olApp = Nothing
End Sub