编辑Excel VBA模块以仅通过电子邮件发送工作表的最后一行

时间:2017-07-07 18:06:49

标签: excel vba excel-vba

我正在尝试编辑这个已经略微编辑过的代码(来源:Ron de Bruin)。现在它通过电子邮件发送电子表格中的所有个人。我希望它只需在For循环中执行一次该函数;在最后一排。作为VBA的新手,这已经证明是困难的。

Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim sh As Worksheet
    Dim cell As Range
    Dim FileCell As Range
    Dim rng As Range

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

    Set sh = Sheets("Sheet1")

    Set OutApp = CreateObject("Outlook.Application")

    For Each cell In sh.Columns("C").Cells.SpecialCells(xlCellTypeConstants)

        'Enter the path/file names in the C:Z column in each row
        Set rng = sh.Cells(cell.Row, 1).Range("D1:Z1")

        If cell.Value Like "?*@?*.?*" And _
           Application.WorksheetFunction.CountA(rng) > 0 Then
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .to = cell.Value
                .Subject = "Testfile"
                .Body = "Hi " & cell.Offset(0, -2).Value

                For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
                     If Trim(FileCell) <> "" Then
                        If Dir(FileCell.Value) <> "" Then
                            .Attachments.Add FileCell.Value
                        End If
                    End If
                Next FileCell

                .Send  'Or use .Display
            End With

            Set OutMail = Nothing
        End If
    Next cell

    Set OutApp = Nothing
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub

为了给出更多的上下文,我试图将这个模块与UserForm结合起来让个人输入他们的信息以及他们希望通过电子邮件发送给他们的附件,当它提交时,它会添加他们的信息到电子表格同时向他们发送附件。

在代码的当前配置中,它会这样做,但每次提交新条目时它也会向每个人发送电子邮件。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用循环查找姓氏,并将If语句放在循环之外,并仅为此使用邮件代码。

If cell.Value Like "?*@?*.?*" And _
  Application.WorksheetFunction.CountA(rng) > 0 Then 
    Set OutMail = OutApp.CreateItem(0)