【问题标题】:Working with Excel VBA Application.ontime function & recursive function call使用 Excel VBA Application.ontime 函数和递归函数调用
【发布时间】:2017-08-01 12:55:54
【问题描述】:

我正在开发一个应用程序,用于为文件夹中的文档发送警报。当使用任务计划程序打开工作簿时,它会调用一个宏-'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

【问题讨论】:

  • 打开工作簿时,同时调用startappsendreminder。然后从 startapp 子例程中删除有关调度 sendreminder 的代码,并将其放入 sendreminder 子例程中。
  • (我假设在第一个小时过去之前不会每 2 分钟发送一次提醒。)
  • 我在 OnWorkbookopen() 中安排了 sendreminder() 并将其从 startapp() 中删除。我保持另一个相同。打开工作簿后,它第一次发送电子邮件,然后 1 小时后没有任何反应。我们是否将召回设置为这个例程?
  • 您需要将有关调度sendreminder(从startapp 中删除)的代码放入sendreminder,如果没有,sendreminder 将运行一次但永远不会重新调度。 OnTime 不是说“小时运行一次”,而是说“一小时内运行这个”——即它安排子例程的单次执行,所以如果您想再次运行子程序,则需要重复 OnTime 命令。

标签: excel recursion vba


【解决方案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

【讨论】:

  • 我也是这样做的,它对我来说效果最好。非常感谢 YowE3K。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多