'Adding a condition bypass (email) logic when (email address) data is not available

I made VBA code for saving a pdf version of payslips and sending it to the staff.

Sub Printsalarypayslip()

    Dim Oapp As Outlook.Application
    Dim Omail As Object
    Dim b As String
        
    a = 1
      
    Do While a <= 33
        
        EMPID = Sheet1.Range("b9").Offset(a, 0).Value
        Sheet2.Range("c3").Value = EMPID
        
        Filename = Sheet2.Range("c3").Value & " - " & Range("c4").Value & ".PDF"
        
        Sheet2.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & Filename
        
        Set Oapp = New Outlook.Application
        Set Omail = Oapp.CreateItem(0)
        
        Oapp.Session.Logon
        
        With Omail
            .to = Sheet2.Range("c6").Value
            .CC = ""
            .Subject = "Monthly Payslip for the Month of Jan 2022"
            .Body = "Dear " & Sheet2.Range("c4").Value & "," & vbNewLine & vbNewLine & "Please Find enclosed Salary Slip for the month of January 2022"
            .Attachments.Add (ThisWorkbook.Path & "\" & Filename)
            .Display
        End With
                
        a = a + 1
        
    Loop

End Sub

I got many errors adding an If.

I need to specify if the cell has no email then escape the process and the "a" value should be + 1.



Solution 1:[1]

You could do something similar to the below. If the email is empty

Do While a <= 33
    EMPID = Sheet1.Range("b9").Offset(a, 0).Value
    Sheet2.Range("c3").Value = EMPID
    
    Filename = Sheet2.Range("c3").Value & " - " & Range("c4").Value & ".PDF"
    
    Sheet2.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & Filename
    a = a + 1
    If IsEmpty(Sheet2.Range("c6").Value) =  False Then
        # You current code to send a mail

It will skip your code if it is empty but still increment a. This suppose that the email is in "c6" since you use it in the "to" attribute.

Note, the instantiation for the Outlook session it would likely be better if you put it before the While loop to avoid creating a new one for each email. If you want to do big volumes it will be faster.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1