[英]Excel VBA: Application.OnTime Not Executing Properly
我試圖從某個時間點到某個結束時間點,以非常短的間隔(例如每秒)運行某個宏。 這意味着我需要一個起點和一個起點。 我無法使用Workbook_Open() Event
,因為在打開工作簿后,我已經有其他宏在不同時間觸發。
我每秒觸發一次宏的基本代碼是此偽代碼:
Application.OnTime Now + TimeValue("00:00:01"), "Path to Macro"
從到目前為止的實驗來看,我所做的任何嘗試最終都有兩個結果。 在第一種情況下,它是從我打開工作簿的那一刻起運行的,並以每秒一次的適當時間表運行。 但是,第一種情況不是最佳的,因為我需要稍等片刻才能啟動。 在第二種情況下,它是在我希望它啟動時運行的-但它只運行了一次,這也不是我想要的。
總結一下:
我需要類似代碼行的內容,以便在打開工作簿后15分鍾開始運行,並在3小時后停止運行。
還有哪些其他定時宏是從workbook_open開始的,為什么這些干擾宏? 聽起來您正在不必要地限制自己。 解決問題的方法如下:
Workbook_open應該使用application.ontime來調用通用函數do_timed_events。 每次運行do_timed_events函數時,應使用application.ontime重新添加自身。 它還應該跟蹤狀態。 對於前幾次運行,它應該執行其他特定任務,然后等待15m,然后開始執行每秒的任務。
這是一些偽代碼:
private var do_timed_events_state as string
sub do_timed_events
if do_timed_events_state = "" then
do_task_1(arg1,arg2)
do_timed_events_state = "task_2"
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
elseif do_timed_events_state = "task_2" then
do_timed_events_state = "repeating_task"
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
elseif do_timed_events_state = "repeating_task" then
Application.OnTime Now + TimeValue("00:00:01"), "do_timed_events"
end if
end sub
在這一方面,您可能會想出比我更好的設計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.