Microsoft Excel - Using VBA to send email with a loop

0

This code filters an Excel sheet by last name, copies that data into a new workbook, then does a Vlookup on sheet 2 to match the last name with an email, and sends an email to that person. I edited the code to input body text for the email.

I am getting the error: Invalid next control variable reference. Any ideas what I am doing wrong??

I had it working perfectly before, but I could not send body text in the email.

The line of code for the troublesome section was originally:

            'Save, Mail, Close and Delete the file
            With NewWB
                .SaveAs TempFilePath & TempFileName _
                      & FileExtStr, FileFormat:=FileFormatNum
                On Error Resume Next
                For I = 1 To 3
                .SendMail mailAddress, _
                              "Subject Line Here"
                    If Err.Number = 0 Then Exit For
                Next I

                On Error GoTo 0
                .Close SaveChanges:=False
            End With

Sub Send_Row_Or_Rows_Attachment_1()
'For Tips see: http://www.rondebruin.nl/win/winmail/div/tips.htm
'Working in Excel 2000-2016
    Dim rng As Range
    Dim Ash As Worksheet
    Dim Cws As Worksheet
    Dim Rcount As Long
    Dim Rnum As Long
    Dim FilterRange As Range
    Dim FieldNum As Integer
    Dim mailAddress As String
    Dim NewWB As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim I As Long
    Dim OutApp As Object
    Dim OutMail As Object


    On Error GoTo cleanup

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    'Set filter sheet, you can also use Sheets("MySheet")
    Set Ash = ActiveSheet

    'Set filter range and filter column (column with names)
    Set FilterRange = Ash.Range("A1:H" & Ash.Rows.Count)
    FieldNum = 1    'Filter column = A because the filter range start in column A

    'Add a worksheet for the unique list and copy the unique list in A1
    Set Cws = Worksheets.Add
    FilterRange.Columns(FieldNum).AdvancedFilter _
            Action:=xlFilterCopy, _
            CopyToRange:=Cws.Range("A1"), _
            CriteriaRange:="", Unique:=True

    'Count of the unique values + the header cell
    Rcount = Application.WorksheetFunction.CountA(Cws.Columns(1))

    'If there are unique values start the loop
    If Rcount >= 2 Then
        For Rnum = 2 To Rcount

            'Look for the mail address in the MailInfo worksheet
            mailAddress = ""
            On Error Resume Next
            mailAddress = Application.WorksheetFunction. _
                          VLookup(Cws.Cells(Rnum, 1).Value, _
                                  Worksheets("Mailinfo").Range("A1:B" & _
                                      Worksheets("Mailinfo").Rows.Count), 2, False)
            On Error GoTo 0

            If mailAddress <> "" Then

                'Filter the FilterRange on the FieldNum column
                FilterRange.AutoFilter Field:=FieldNum, _
                                       Criteria1:=Cws.Cells(Rnum, 1).Value

                'Copy the visible data in a new workbook
                With Ash.AutoFilter.Range
                    On Error Resume Next
                    Set rng = .SpecialCells(xlCellTypeVisible)
                    On Error GoTo 0
                End With

                Set NewWB = Workbooks.Add(xlWBATWorksheet)

                rng.Copy
                With NewWB.Sheets(1)
                    .Cells(1).PasteSpecial Paste:=8
                    .Cells(1).PasteSpecial Paste:=xlPasteValues
                    .Cells(1).PasteSpecial Paste:=xlPasteFormats
                    .Cells(1).Select
                    Application.CutCopyMode = False
                End With

                'Create a file name
                TempFilePath = Environ$("temp") & "\"
                TempFileName = "Overdue STAS Plans" & Ash.Parent.Name _
                             & " " & Format(Now, "dd-mmm-yy h-mm-ss")

                If Val(Application.Version) < 12 Then
                    'You use Excel 97-2003
                    FileExtStr = ".xls": FileFormatNum = -4143
                Else
                    'You use Excel 2007-2016
                    FileExtStr = ".xlsx": FileFormatNum = 51
                End If

                Set OutApp = CreateObject("Outlook.Application")
                Set OutMail = OutApp.CreateItem(0)

                On Error Resume Next

                'Save, Mail, Close and Delete the file
                With NewWB
                    .SaveAs TempFilePath & TempFileName _
                          & FileExtStr, FileFormat:=FileFormatNum
                                        On Error Resume Next
                    For I = 1 To 3
                        Next OutMail
                            .To = "mailAddress"
                            .CC = ""
                            .BCC = ""
                            .Subject = ""
                            .Body = "hi"
                            .Attachments.Add.TempFileName
                            .Display
                        End With

                        If Err.Number = 0 Then Exit For
                        Next I

                    On Error GoTo 0
                    .Close SaveChanges:=False

                End With

                'Delete the file you have send
                Kill TempFilePath & TempFileName & FileExtStr

                End If

            'Close AutoFilter
            Ash.AutoFilterMode = False

        Next Rnum
    End If

cleanup:
    Application.DisplayAlerts = False
    Cws.Delete
    Application.DisplayAlerts = True

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub

Ryan DeQuintal

Posted 2016-08-15T13:08:03.150

Reputation: 1

Answers

0

You've a strange Next:

 For I = 1 To 
     Next OutMail

probably you wanted to write With

Máté Juhász

Posted 2016-08-15T13:08:03.150

Reputation: 16 807