Search code examples
excelemail-attachmentscdo.messagevba

Create new attachments Excel-VBA


does anyone know how to remove an attachment object from VBA? i'm trying to do an application in Excel using VBA such it will will send emails depending on the data found on the excel file. In my code below, the emails are sent, however, the last email has all the attachments from the previous ones. Any help would be appreciated.

Private Sub btnSendEmail_Click()
For Counter = 2 To 3
    Dim Mail As New Message
    Dim Config As New Configuration
    Set Config = Mail.Configuration
    Config(cdoSendUsingMethod) = cdoSendUsingPort
    Config(cdoSMTPServer) = "smtp.gmail.com"
    Config(cdoSMTPServerPort) = 465
    Config(cdoSMTPAuthenticate) = cdoBasic
    Config(cdoSMTPUseSSL) = True
    Config(cdoSendUserName) = "[email protected]"
    Config(cdoSendPassword) = "test"
    Config.Fields.Update
    Set curFirstName = Worksheets("Sheet1").Cells(Counter, 1)
    Set curLastName = Worksheets("Sheet1").Cells(Counter, 2)
    Set curEmail = Worksheets("Sheet1").Cells(Counter, 3)
    Set curAttach = Worksheets("Sheet1").Cells(Counter, 4)
    Mail.To = curEmail.Value
    Mail.From = Config(cdoSendUserName)
    Mail.Subject = "This is a test!"
    Mail.HTMLBody = "<h1>" & curFirstName.Value & " " & curLastName.Value & "</h1>"
    Mail.AddAttachment curAttach.Value
    Mail.Send
Next Counter
MsgBox "Sent"
End Sub

Solution

  • The following line of code should work:

    Mail.Attachments.DeleteAll