You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Excel宏每日自动运行,截止日前7天自动发送Outlook提醒

实现Excel生日提醒宏每日自动运行的方案

你可以根据使用场景选择以下两种方案实现自动运行:


方案1:使用Excel内置的Application.OnTime定时调度(适合Excel长期后台运行的场景)

操作步骤:

  • 第一步:拆分原有代码,将业务逻辑抽为公共可调用的子过程
    插入一个标准模块,粘贴以下代码:
    ' 放在标准模块中(比如模块1)
    Public nextRunTime As Date ' 存储下次运行时间的全局变量
    
    Public Sub SendBirthdayReminder()
        Dim i As Long
        Dim OutApp As Object, OutMail As Object
        Dim strto As String, strcc As String, strbcc As String, strsub As String, strbody As String
            
        Set OutApp = CreateObject("Outlook.Application")
        OutApp.Session.Logon
        Set OutMail = OutApp.CreateItem(0)
            
        For i = 2 To Range("e65536").End(xlUp).Row
            If Cells(i, 9) <> "Y" Then
                If Cells(i, 5) - 7 < Date Then
                        
                    strto = Cells(i, 7).Value '收件人邮箱
                    strsub = Cells(i, 1).Value & " " & Cells(i, 2).Value & " compleanno il " & Cells(i, 5).Value '邮件主题
                    strbody = "Il compleanno di " & Cells(i, 1).Value & " " & Cells(i, 2).Value & " sarà il " & Cells(i, 5).Value & vbNewLine '邮件正文
                        
                    With OutMail
                        .To = strto
                        .Subject = strsub
                        .Body = strbody
                        .Send 
                    End With
                        
                    Cells(i, 8) = "Mail Sent " & Now()
                    Cells(i, 9) = "Y"
                        
                End If
            End If
        Next
            
        Set OutMail = Nothing
        Set OutApp = Nothing
    
        ' 执行完成后,注册明天同一时间的运行任务
        nextRunTime = Now + TimeValue("24:00:00")
        Application.OnTime nextRunTime, "SendBirthdayReminder"
    End Sub
    
  • 第二步:配置工作簿打开/关闭的事件逻辑
    打开ThisWorkbook模块,粘贴以下代码:
    ' 放在ThisWorkbook模块中
    Private Sub Workbook_Open()
        ' 工作簿打开时立即执行一次提醒,同时注册明天的定时任务
        Call SendBirthdayReminder
    End Sub
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
        ' 工作簿关闭时取消未执行的定时任务,避免Excel报错
        On Error Resume Next
        Application.OnTime nextRunTime, "SendBirthdayReminder", , False
        On Error GoTo 0
    End Sub
    

注意:该方案需要保持Excel文件一直处于打开状态,定时任务才会正常触发,关闭Excel后调度会失效。


方案2:结合Windows任务计划程序实现定时触发(不需要长期打开Excel)

如果不想一直后台挂着Excel,可以用系统级的定时任务触发:

  1. 调整上面SendBirthdayReminder的代码,在最后追加自动保存关闭的逻辑:
    ' 执行完提醒后自动保存修改并关闭Excel
    ThisWorkbook.Save
    Application.Quit
    
  2. 打开Windows「任务计划程序」创建新任务:
    • 触发器设置为每天需要发送提醒的固定时间
    • 操作设置为「启动程序」,程序路径选择Excel的安装路径,参数填写提醒表格的完整绝对路径,例如"C:\Users\XXX\Desktop\生日提醒表.xlsm"
    • 可选勾选「不管用户是否登录都要运行」,实现后台静默执行

注意:需要将Excel的宏安全级别调整为允许该文件的宏运行,避免执行被拦截。


内容的提问来源于stack exchange,提问作者Umberto Roselli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:36:03