使用Excel VBA Application.ontime功能&递归函数调用

时间:2017-08-01 03:39:08

标签: excel-vba recursion vba excel

我正在开发一个应用程序,用于发送文件夹中文档的警报。当使用任务调度程序打开工作簿时,它会调用一个宏-'startapp'。在startapp()中,它会在每2分钟后检查文件夹中的新文件并发送电子邮件/通知。在同一个宏中,有一个调用另一个函数,该函数每隔1小时发送一次文件夹中待处理文件的提醒。我已设置递归调用startapp(),以便应用程序处于连续处理状态。有一个错误:在运行时,宏会在每2分钟后发送新文档和提醒的警报。我希望应用程序在1小时后发送提醒。请检查以下代码。

Public Sub startapp()

Call checkuser(i)                    
'finds lastrow and user email for incoming files

Call checklist(i)             
'check new in files according to user selected in the list and send emails

rtime = Now + TimeValue("01:00:00")


Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:="true"         
 'sendreminder for files in in folder

starttime = Now + TimeValue("00:02:00")


Application.OnTime EarliestTime:=starttime, Procedure:="startapp", Schedule:="true"


End Sub

1 个答案:

答案 0 :(得分:1)

我建议您按如下方式设置代码:

Private Sub Workbook_Open()
    startapp
    sendreminder
End Sub

Public Sub startapp()
    checkuser i
    'finds lastrow and user email for incoming files

    checklist i
    'check new in files according to user selected in the list and send emails

    starttime = Now + TimeValue("00:02:00")
    Application.OnTime EarliestTime:=starttime, _
                       Procedure:="startapp", _
                       Schedule:=True    
End Sub

Public Sub sendreminder()
    '...
    ' whatever code you currently have
    '...

    rtime = Now + TimeValue("01:00:00")
    Application.OnTime EarliestTime:=rtime, _
                       Procedure:="sendreminder", _
                       Schedule:=True    
End Sub