I need someone to amend my VBA Code to generate an email for sheets Br1 to last sheet. My sample data has only 3 sheets to be generated in Outlook , but by live data has 20 sheets
The Subject is named "subjectText1" on sheet "Email Branches" and Body is named "Bodytext1" I need a seperate email for each sheet from "Br1" to the last sheet. The email addresses are in AA1 to AA5 on each of these sheets. The email must only be created for each sheet where the average value in Col E2:E3 does exceed 60
I get Method or data member not found
It would be appreciated if someone could kindly check and amend my code
OutlookMail.Attachments.Add AttachedSheet.FullName
Sub GenerateEmails()
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim ws As Worksheet
Dim rngEmail As Range
Dim avgDays As Variant
Dim Ztext As String
Dim Zsubject As String
Dim AttachedSheet As Worksheet
Dim sheetCounter As Integer
' Create Outlook application
Set OutlookApp = CreateObject("Outlook.Application")
' Initialize sheet counter
sheetCounter = 1
For Each ws In ThisWorkbook.Sheets
If ws.Name >= "BR1"
' Check average value in Col E2:E3
On Error Resume Next
avgDays = Application.WorksheetFunction.Average(ws.Range("E2:E3"))
On Error GoTo 0
If IsNumeric(avgDays) And avgDays > 60 Then ' Only proceed if average exceeds 60 days
' Get email addresses from AA1 to AA5 on the current sheet
Set rngEmail = ws.Range("AA1:AA5")
' Set subject and body text using a more direct approach
Zsubject = ThisWorkbook.Sheets("Email Branches").Range("SubjectText1").Value
Ztext = ThisWorkbook.Sheets("Email Branches").Range("BodyText1").Value
' Loop through each email address and create an email
For Each cell In rngEmail
If cell.Value <> "" Then ' Check if the cell is not empty
' Create a new email
Set OutlookMail = OutlookApp.CreateItem(0)
' Set email properties using additional variables
OutlookMail.Subject = Zsubject
OutlookMail.Body = Ztext
OutlookMail.To = cell.Value
' Attach the current sheet with a unique name
ws.Copy Before:=Sheets(1)
Set AttachedSheet = Sheets(1)
AttachedSheet.Name = "AttachmentSheet" & sheetCounter
sheetCounter = sheetCounter + 1
' Attach the copied sheet to the email
OutlookMail.Attachments.Add AttachedSheet.FullName
' Display the email (you can remove or replace this line if you want to send without displaying)
OutlookMail.Display
' Release the email object
Set OutlookMail = Nothing
' Delete the temporary copied sheet
Application.DisplayAlerts = False
AttachedSheet.Delete
Application.DisplayAlerts = True
End If
Next cell
End If
End If
Next ws
' Release the Outlook application object
Set OutlookApp = Nothing
End Sub
Bookmarks