Filter data and send Mail

atuljadhavnetafim

Active Member
Joined
Apr 7, 2012
Messages
341
Office Version
  1. 365
Platform
  1. Windows
Dear Expert,

I have one file which has two sheet
1) Customer, which has below data


2) Data, which has below data

RegistryAccountPayment_TermsInvoice NoGST Invoice NoInvoice_DateDue_DateAmount
186205​
71267​
PDC60N
2201044711​
GJ28KS2122100038
31-May-21​
31-May-21​
4,93,985
186205​
71267​
PDC60N
2201044719​
GJ28KS2122100038
30-Sep-21​
30-Sep-21​
9,63,244
186205​
71267​
PDC60N
2201044718​
GJ28KS2122100038
30-Sep-21​
30-Sep-21​
5,74,725
186205​
71267​
PDC60N
2201044717​
GJ28KS2122100038
30-May-22​
30-Sep-21​
4,64,405
266712​
107269​
PDC60N
2201044716​
GJ28KS2122100038
27-Jul-22​
30-Sep-21​
4,30,610
266712​
83700​
PDC60N
2201044715​
GJ28KS2122100038
17-Jul-21​
16-Aug-21​
2,15,026
80151​
67192​
PDC60N
2303030063​
GJ28KS2122100038
29-Jun-22​
29-Jun-22​
8,02,553
80151​
67192​
PDC60N
2218164682​
GJ28KS2122100038
30-Jun-22​
29-Jun-22​
1,37,410
80151​
67192​
PDC60N
2301060310​
KA711S2223103383
05-Jul-22​
03-Sep-22​
4,98,422
80151​
67192​
PDC60N
2301088154​
KA711S2223105107
17-Aug-22​
16-Oct-22​
2,62,085
234852​
94859​
10%A90%60D
2301057313​
GJ28GE2223100029
29-Jun-22​
28-Aug-22​
4,01,098
234852​
94859​
10%A90%60D
2301059888​
GJ28GE2223100035
02-Jul-22​
31-Aug-22​
8,12,067
234852​
94859​
10%A90%60D
2301059887​
GJ28GE2223100036
02-Jul-22​
31-Aug-22​
6,75,869
234852​
94859​
10%A90%60D
2301059889​
GJ28GE2223100037
02-Jul-22​
31-Aug-22​
5,72,337

Now i want to send email to all customer who are in customer sheet and filter data from "Data" sheet and send result in body to that particular email address as mentioned in "To" and "CC".
till last customer in "Customer" sheet.

can any one give me link/file
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
paste code into a module, start Outlook, then run : SendAllEmails
it will filter the data then send it to those in the To & CC list.
It stores the separated data sheets in c:\temp\

Code:
Option Explicit

Public gvFile
Public gcolEmails As New Collection
Public Const kTempDir = "c:\temp\"

Sub FilterRecs()
Range("A1").Select
    ActiveSheet.UsedRange.Select
    Selection.AutoFilter
    ActiveSheet.UsedRange.AutoFilter Field:=2, Criteria1:="Arkham"
End Sub
Sub CopyData2Send()
' ExportData2eMail Macro
Dim wsNew As Worksheet

    gvFile = "C:\temp\file1email.xlsx"
   
    ActiveSheet.UsedRange.Select
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    Set wsNew = ActiveSheet
   
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    Cells.Select
    Cells.EntireColumn.AutoFit
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Application.CutCopyMode = False
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.249977111117893
        .PatternTintAndShade = 0
    End With
    Range("A1").Select

    wsNew.Select
    wsNew.Copy
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=gvFile, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False      ', ConflictResolution:=True
    Application.DisplayAlerts = True
    ActiveWindow.Close

Set wsNew = Nothing
End Sub



Public Function Send1Email(ByVal pvTo, ByVal pvSubj, ByVal pvBody, ByVal pvCC, Optional ByVal pvFile) As Boolean
Dim oMail As Outlook.MailItem
Dim oApp As Outlook.Application

On Error GoTo ErrMail

'NOTE : YOU MUST HAVE THE OUTLOOK X.x Object Library    REFERENCE CHECKED IN VBE; ctl-G, menu,tools, references, Microsoft Outlook XX Object library

Set oApp = GetApplication("Outlook.Application")  'it may be open already so use this
'Set oApp = CreateObject("Outlook.Application")  'not this

Set oMail = oApp.CreateItem(olMailItem)
With oMail
    .To = pvTo
    .CC = pvCC
    .Subject = pvSubj
   
    If Not IsMissing(pvFile) Then .Attachments.Add pvFile, olByValue, 1
   
    .HTMLBody = pvBody
    '=RangetoHTML(rng)     'vBody will not paste XL range in the format
   
     If Not IsNull(pvBody) Then .Body = pvBody
   
    .Display True
    '.Send
End With

Send1Email = True
endit:
Set oMail = Nothing
Set oApp = Nothing
Exit Function

ErrMail:
MsgBox Err.Description, vbCritical, Err
Resume endit
End Function


Function GetApplication(className As String) As Object
' function to encapsulate the instantiation of an application object
Dim theApp As Object
On Error Resume Next
Set theApp = GetObject(, className)
If Err.Number <> 0 Then
    MsgBox "Unable to Get" & className & ", attempting to CreateObject"
    Set theApp = CreateObject(className)
End If

If theApp Is Nothing Then
    Err.Raise Err.Number, Err.Source, "Unable to Get or Create the " & className & "!"
    Set GetApplication = Nothing
End If

'MsgBox "Successfully got a handle on Outlook Application, returning to caller"
Set GetApplication = theApp
End Function


Public Sub collectEmailList()
Dim vTo, vWord, vName, vEmail, vReg, vCC

On Error GoTo errAdd
MakeDir kTempDir
Set gcolEmails = New Collection
Sheets("Customer").Activate    'goto the email list
       
        'cycle thru the list of email addrs
Range("A2").Select
While ActiveCell.Value <> ""
    vReg = "r" & ActiveCell.Offset(0, 0).Value
    If Right(vReg, 1) = "?" Then vReg = Left(vReg, Len(vReg) - 1)
   
    vEmail = ActiveCell.Offset(0, 1).Value
    vCC = ActiveCell.Offset(0, 2).Value
   
    vWord = vReg & "~" & vEmail & "~" & vCC
   
    gcolEmails.Add vWord, vReg      'add email to collection
    ActiveCell.Offset(1, 0).Select 'next row
Wend

 'free memory
'Set gcolEmails = Nothing
Exit Sub
errAdd:
If Err = 457 Then Resume Next   'prevent error for dupes
MsgBox Err.Description, , Err
End Sub

    'convert the uniq collection into a list for email
Public Function BuildBulkLIst()
Dim i As Integer
Dim vEList

For i = 1 To gcolEmails.Count
  vEList = vEList & gcolEmails(i) & ";"
Next
BuildBulkLIst = vEList
MsgBox vEList

End Function

Private Function split1UserEmail(ByVal pvWord, pvReg, pvEmail, pvCC)
Dim vEmail
Dim i As Integer

i = InStr(pvWord, "~")
pvReg = Left(pvWord, i - 1)
pvReg = Mid(pvReg, 2)
pvWord = Mid(pvWord, i + 1)


i = InStr(pvWord, "~")
pvEmail = Left(pvWord, i - 1)
pvCC = Mid(pvWord, i + 1)

split1UserEmail = pvReg
End Function

Private Function get1UserEmailViaName(ByVal pvName)
Dim vEmail, vWord
vWord = gcolEmails(pvName)
'pvName = Mid(vWord, InStr(vWord, "~") + 1)
vEmail = Mid(vWord, InStr(vWord, "~") + 1)
get1UserEmailViaName = vEmail
End Function

Public Sub SendAllEmails()
Dim i As Integer
Dim vEmail, vReg, vCC

MsgBox "Have Outlook open."
SetWarnings False

collectEmailList   'gather all emails

For i = 1 To gcolEmails.Count
   vReg = ""
   Call split1UserEmail(gcolEmails(i), vReg, vEmail, vCC)
  
   'Debug.Print "Dear " & vName & ", via: " & vEmail
   Filter1Name vReg, vEmail, vCC
Next
SetWarnings True

End Sub

Sub Filter1Name(ByVal pvReg, ByVal pvTo, ByVal pvCC)
Dim rng As Range
Dim r As Long
Dim vSubj, vBody, vFile
Dim wbTarg As Workbook


    Sheets("Data").Activate
    Range("A1").Select
    Set rng = ActiveSheet.UsedRange
   
    Selection.AutoFilter
    rng.AutoFilter Field:=1, Criteria1:=pvReg
             'select FILTERED recs only
    rng.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
   
       'FAIL:
    
     'vBody = PasteClipboardText()   'requires FM20.dll as a reference.
    
    Workbooks.Add
    Set wbTarg = ActiveWorkbook
    ActiveCell.PasteSpecial xlPasteValues
   
     r = rng.Cells.SpecialCells(xlCellTypeVisible).Rows.Count
   
    vFile = kTempDir & pvReg & "_Data.xls"
    KillFile vFile
    wbTarg.SaveAs vFile, 39
    wbTarg.Close True
    
   
     If r > 1 Then    'dont send if no data
            '--------- pastge to new workBOOK
                'Selection.Copy
                'Workbooks.Add
                'ActiveSheet.Paste
                'Application.CutCopyMode = False
               
                'ActiveWorkbook.SaveAs Filename:=vFILE, FileFormat:=xlExcel8, CreateBackup:=False
                'ActiveWindow.Close
   
              '--------PASTE DATA TO NEW SHEET
            'Sheets.Add After:=ActiveSheet
            'ActiveCell.PasteSpecial xlPasteAll
            'ActiveSheet.Name = pvName
           
           
            'EMAIL THE DATA
            vSubj = "Dear " & pvReg & vbCrLf & "here is your data:"
              'format fail: vBody = PasteClipboardText()
            vBody = "data attached"
              
           Debug.Print "send " & pvReg, pvTo
          
            Send1Email pvTo, vSubj, vBody, pvCC, vFile
           
    End If
   
   
    Sheets("Data").Activate
    Application.CutCopyMode = False
   
    Selection.AutoFilter   'filter off
End Sub


'Function PasteClipboardText()
''FM20.dll
' 'reference to Microsoft Forms 2.0 Object Library. If its not listed, add C:\Windows\System32\FM20.dll or C:\Windows\FM20.dll as a reference.
'Dim DataObj As MSForms.DataObject
'Set DataObj = New MSForms.DataObject
'
'DataObj.GetFromClipboard
'PasteClipboardText = DataObj.GetText(1)
'End Function

Public Sub KillFile(ByVal pvFile)
Dim fso
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
'FileReadOnly pvFile, False
fso.DeleteFile pvFile
Set fso = Nothing
End Sub

Private Sub SetWarnings(ByVal pbOn As Boolean)
   Application.DisplayAlerts = pbOn    'turn off sheet compatability msg
   Application.EnableEvents = pbOn
   Application.ScreenUpdating = pbOn
End Sub




Public Sub MakeDir(ByVal pvDir)
Dim fso
On Error GoTo errMake
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(pvDir) Then fso.CreateFolder pvDir     'MkDir pvDir
Set fso = Nothing
Exit Sub
errMake:
'MsgBox Err.Description & vbCrLf & pvDir, , "MakeDir(): " & Err
Set fso = Nothing
End Sub
 
Upvote 0
Hi, Thanks for your reply, but have some issue.

i have made changes, used ".Send" instead of ".Display".

after running this code, it send only one email for customer code 186205 then stop.
it is not run for remaining codes in customer master, i think loop not happening till last customer.

rest thing working as expected.

thanks, please resolve this so i can start to use this.
 
Upvote 0

Forum statistics

Threads
1,223,918
Messages
6,175,365
Members
452,638
Latest member
Oluwabukunmi

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