Search code examples
vbaoutlookuserform

How to send emails with conditional attachments?


When you use a userform in VBA to send an email is there an option to conditionally add an attachment?

Example userform

Let's say

  • if checkboxes 1 & 2 are checked, IMG1 will be attached
  • if checkbox 3 is checked, IMG2 will be attached
  • If checkboxes 1, 2 and 3 are checked, IMG1 and IMG2 will be attached
Private Sub CommandButton1_Click()
    Dim AppOutlook As Outlook.application
    Dim Mailtje As Outlook.MailItem
    Dim strbody As String
    Set AppOutlook = CreateObject("Outlook.Application")
    Set Mailtje = AppOutlook.CreateItem(olMailItem)

    Mailtje.Display
    Mailtje.To = TextBox1.Value
    Mailtje.CC = TextBox2.Value
    Mailtje.Subject = "Test" & Format(Date, "dd/mm/yy")
    Mailtje.HTMLBody = strbody
    .Attachments.Add = IMG1.jpg
End Sub

Solution

  • Something like this:

    If checkbox1.Value And checkbox2.Value Then
        Mailtje.Attachments.Add "C:\Test\Pic1.jpg" 'use the full path
    End If
    If checkbox3.Value Then
        Mailtje.Attachments.Add "C:\Test\Pic2.jpg"
    End If