【发布时间】:2014-05-27 07:28:06
【问题描述】:
我试图在我的 sub 中使用多个 Application.OnTime,但我得到了意想不到的结果。
这就是我想做的:
-
使用“递归”调用每 1 分钟运行一次子 (testOnTime)
内部子(testOnTime):
-
进入 sub (testOnTime) 10 秒后运行“firstSection”
“firstSection”内部:将调试消息写入 Excel 工作表“MySheet”
-
进入 sub (testOnTime) 40 秒后运行“lastSection”
“lastSection”内部:将调试消息写入 Excel 工作表“MySheet”
将调试消息写入 Excel 工作表“Mysheet”
是否有 sub "testOnTime" 运行 5 次?:否 -> 继续,是 -> 退出
-
代码:
Option Explicit
Public rowCnt As Integer
Public Cnt As Integer
Public Const sheetName = "MySheet"
Public Const inc1 = "00:00:40"
Public Const inc2 = "00:00:10"
Public timeStr1 As Date
Public timeStr2 As Date
Public timeStr3 As Date
Public Sub MyMain()
rowCnt = 1
Cnt = 0
Call testOnTime
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "Done"
End Sub
Public Sub testOnTime()
' wait-time for last section
timeStr1 = Format(Now + TimeValue(inc1), "hh:mm:ss")
' wait time for first section
timeStr2 = Format(Now + TimeValue(inc2), "hh:mm:ss")
' wait for 1 minute
timeStr3 = Format(Now + TimeValue("00:01:00"), "hh:mm:ss")
' wait utill 10 seconds
Application.OnTime TimeValue(timeStr2), "firstSection"
' wait utill 40 seconds
Application.OnTime TimeValue(timeStr1), "lastSection"
' debug msgs
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "Outside @ " & CStr(timeStr3)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
Cnt = Cnt + 1
If Cnt < 5 Then
' wait until Now + 1 min
Application.OnTime TimeValue(timeStr3), "testOnTime"
End If
End Sub
Public Sub firstSection()
' debug msgs for first section
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "In first section @ " & CStr(timeStr2)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
End Sub
Public Sub lastSection()
' debug msgs for first section
Worksheets(sheetName).Range("A" & CStr(rowCnt)).Value = "In last section @ " & CStr(timeStr1)
Worksheets(sheetName).Range("B" & CStr(rowCnt)).Value = CStr(rowCnt)
Worksheets(sheetName).Range("C" & CStr(rowCnt)).Value = CStr(Cnt)
rowCnt = rowCnt + 1
End Sub
为什么“外部...”应该是宏内部的最后一条指令,但它会首先写入 Excel 工作表?
为什么宏应该只输出一次却输出“两个”相同的信息?
有没有更好的方法可以在不使用“OnTime”的情况下实现我的预期目标?
【问题讨论】:
-
公共变量太多,调用 subs 时没有参数,整数应该很长,未声明 sheetname,我无法停止编程错误,rowcnt 应该在每个循环中重新测试它自己的工作表@ 987654323@