vba condition email

ashani

Active Member
Joined
Mar 14, 2020
Messages
347
Office Version
  1. 365
Platform
  1. Windows
Hi,

I'm using the below syntax in VBA to send multiple emails with attachments and it's working fine - however I would like the VBA to only send email to those recipients if in Column Y says Yes, if it says No then don't send email. Please could someone guide me. Thank you

Code:
Option Explicit

Sub send_multiple_emails()

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")

Dim OA As Object
Dim msg As Object

Set OA = CreateObject("Outlook.application")

Dim i As Integer
Dim last_row As Integer

last_row = Application.WorksheetFunction.CountA(sh.Range("H:H"))

For i = 2 To last_row
Set msg = OA.createitem(0)

msg.to = sh.Range("H" & i).Value
msg.cc = sh.Range("I" & i).Value
msg.Subject = "Sales Report"
msg.body = sh.Range("M" & i).Value

If sh.Range("J" & i).Value <> "" Then
msg.attachments.Add sh.Range("J" & i).Value
End If

msg.display


Next i


End Sub
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
perhaps
VBA Code:
For i = 2 To last_row
  If ActiveSheet.Range("Y" & i) = "Yes" Then
     Set msg = OA.createitem(0)
     ' more code
  End If
Next
When you don't include the beginning and ending lines (Sub... End Sub) assumptions have to be made. In this case, perhaps ActiveSheet is not correct.
 
Upvote 0
Thank you
If the first row says No then it come up with the error message

1678012442219.png
 
Upvote 0
You need to show what line raises an error. Your code does not error for me, so it might help if you post some data that you're using for this. You can edit it to protect privacy. Copy something from a sheet and paste it into a post?
 
Upvote 0

Forum statistics

Threads
1,223,228
Messages
6,170,871
Members
452,363
Latest member
merico17

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top