通过excel发送电子邮件提醒

时间:2017-03-30 16:21:48

标签: excel vba excel-vba

我正在尝试从Excel发送电子邮件提醒,如果F列中提到的日期早于当前日期的2年。 我在以下命令中收到错误运行时462 。发送 请建议。

Sub send_files()

        Dim OutMail As Object
        Dim sh As Worksheet
        Dim cell As Range
        Dim FileCell As Range
        Dim bottomA As Integer
        Dim x As Integer
        Dim mydate1 As Date
        Dim mydate2 As Long
        Dim datetoday1 As Date
        Dim datetoday2 As Long
        Dim outlookapp As Object



        Set sh = ThisWorkbook.Sheets("Sheet1")

        bottomA = sh.Range("F" & Rows.Count).End(xlUp).Row

        For x = 2 To bottomA

        mydate1 = Cells(x, 6).Value

        mydate2 = mydate1

    Cells(x, 13).Value = mydate2

    datetoday1 = Date

    datetoday2 = datetoday1

    Cells(x, 14).Value = datetoday2

    If datetoday2 - mydate2 >= 730 Then

    Set outlookapp = CreateObject("Outlook.Application")

    Set OutMail = outlookapp.CreateItem(0)

    With OutMail
        .to = Cells(2, 17).Value

        .Subject = "Folder Expiration Alert"

        .Body = "Hi"

        .send

        End With



        End If

        Next

     Set outlookapp = Nothing

    Set OutMail = Nothing


End Sub

1 个答案:

答案 0 :(得分:0)

手动更改单元格时运行宏

要在手动更改特定单元格时自动运行宏,可以使用工作表模块中的“更改”事件。此页面上的示例使用单元格A1,如果单元格值> 200,则将运行宏。

1)右键单击工作表选项卡,然后选择查看代码 2)将下面的事件粘贴到图纸模块中。 3)Alt-q返回Excel

注意:将YourMacroName更改为代码中宏的名称。 如果您希望代码适用于其他单元格或更多单元格,则可以更改事件中的范围。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > 200 Then
            Call YourMacroName
        End If
    End If
End Sub

示例邮件宏

测试此示例宏以使用小文本消息创建/显示Outlook邮件。 您必须在标准模块中而不是在工作表模块中复制此宏,请参阅此页面。

注意:我在代码中使用.Display来显示邮件,你可以将其更改为.Send

不要忘记将Change YourMacroName更改为在Change事件中调用Mail_small_Text_Outlook。

Sub Mail_small_Text_Outlook()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Excel 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String

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

    strbody = "Hi there" & vbNewLine & vbNewLine & _
              "Cell A1 is changed" & vbNewLine & _
              "This is line 2" & vbNewLine & _
              "This is line 3" & vbNewLine & _
              "This is line 4"

    On Error Resume Next
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = strbody
        'You can add a file like this
        '.Attachments.Add ("C:\test.txt")
        .Display   'or use .Send
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

https://www.rondebruin.nl/win/s1/outlook/bmail9.htm