Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending multiple attachments from excel sheet with 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!

like image 360
Thomas Varghese Avatar asked Jan 01 '26 04:01

Thomas Varghese


2 Answers

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 
like image 173
Abhijeet Shukla Avatar answered Jan 04 '26 13:01

Abhijeet Shukla


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 
like image 30
izzymo Avatar answered Jan 04 '26 12:01

izzymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!