2

我有一个在上午 8 点到下午 4 点之间每分钟运行一次的电子表格,它从某个文件夹导入文件并进行某些计算

进行计算以检查是否违反了限制。如果超出限制,则电子表格需要通过声音警报和电子邮件警报通知用户。要求是每分钟发出一次声音警报,而电子邮件警报应该每 45 分钟发出一次,因为他们不想收到垃圾邮件。

public sub fileImport()
     if between 0800 to 1600
         //do file import
         //do calculations
         if breach sound alert             
     end if   
     Application.OnTime RunEveryMinute, fileImport

     if there is a breach
         sendMail()         
         Application.OnTime RunEvery45Min, sendMail              
     end if

public sub sendEmail()
     //do email function

那么我如何才能每 45 分钟而不是每分钟调用一次 sendEmail 子程序呢?

4

2 回答 2

4

假设这是在一个循环中,只需记录最后一次发送时间并将其与Now;

Public Sub sendEmail()
    Static lastSent As Date
    If DateDiff("m", lastSent, Now) > 45 Then
         '//do email function
         lastSent = Now
    End If
End Sub

(这也将在第一次被调用时发送)

于 2012-10-17T15:55:17.310 回答
0

您可以只使用 OnTime 功能:

Public RunWhen As Double
Public Const cRunIntervalSeconds = 120 ' two minutes
Public Const cRunWhat = "TheSub"

Sub StartTimer()
    RunWhen = Now + TimeSerial(0,0,cRunIntervalSeconds)
    Application.OnTime EarliestTime:=RunWhen, Procedure:=cRunWhat, _
        Schedule:=True
End Sub
'This stores the time to run the procedure in the variable RunWhen, two minutes after the current time.

'Next, you need to write the procedure that will be called by OnTime. For example,

Sub TheSub()
    ' Put your send email code here.
    StartTimer  ' Reschedule the procedure
End Sub

这个例子来自:http ://www.cpearson.com/excel/OnTime.aspx

祝你好运。

于 2012-10-17T18:15:23.143 回答