3

一定の間隔でタスクを実行したい古い Excel VBA コードがあります。VB6 を使用していた場合は、タイマー コントロールを使用していたでしょう。

Application.OnTime()メソッドを見つけました。Excel ワークシートで実行されているコードではうまく機能しますが、ユーザー フォームでは機能しません。メソッドが呼び出されることはありません。

Application.OnTime() でユーザー フォームのメソッドを呼び出すにはどうすればよいですか、または VBA でコードを実行するようにスケジュールする他の方法はありますか?

4

4 に答える 4

8

これに対する回避策を見つけました。ユーザー フォームのメソッドを呼び出すだけのメソッドをモジュールに記述する場合は、Application.OnTime() を使用してモジュール メソッドをスケジュールできます。

ちょっと面倒ですが、誰かがより良い提案をしない限り、それで十分です。

次に例を示します。

''//Here's the code that goes in the user form
Dim nextTriggerTime As Date

Private Sub UserForm_Initialize()
    ScheduleNextTrigger
End Sub

Private Sub UserForm_Terminate()
    Application.OnTime nextTriggerTime, "modUserformTimer.OnTimer", Schedule:=False
End Sub

Private Sub ScheduleNextTrigger()
    nextTriggerTime = Now + TimeValue("00:00:01")
    Application.OnTime nextTriggerTime, "modUserformTimer.OnTimer"
End Sub

Public Sub OnTimer()
    ''//... Trigger whatever task you want here

    ''//Then schedule it to run again
    ScheduleNextTrigger
End Sub

''// Now the code in the modUserformTimer module
Public Sub OnTimer()
    MyUserForm.OnTimer
End Sub
于 2009-10-13T21:13:06.943 に答える
0

user1575005 さん、ありがとうございます!!

モジュール内のコードを使用して、Timer() プロセスをセットアップしました。

Dim nextTriggerTime As Date
Dim timerActive As Boolean

Public Sub StartTimer()
Debug.Print Time() & ": Start"
If timerActive = False Then
    timerActive = True
    Call ScheduleNextTrigger
End If
End Sub

Public Sub StopTimer()
 If timerActive = True Then
    timerActive = False
    Application.OnTime nextTriggerTime, "OnTimer", Schedule:=False
End If
Debug.Print Time() & ": End"
End Sub

Private Sub ScheduleNextTrigger()
If timerActive = True Then
    nextTriggerTime = Now + TimeValue("00:00:10")
    Application.OnTime nextTriggerTime, "OnTimer"
End If
End Sub

Public Sub OnTimer()
Call bus_OnTimer
Call ScheduleNextTrigger
End Sub


Public Sub bus_OnTimer()
Debug.Print Time() & ": Tick"
Call doWhateverUwant
End Sub

Private Sub doWhateverUwant()

End Sub
于 2019-10-08T22:12:01.827 に答える
0

すべてのコードを「Timer」モジュールに移動するのはどうですか。

Dim nextTriggerTime As Date
Dim timerActive As Boolean

Public Sub StartTimer()
    If timerActive = False Then
        timerActive = True
        Call ScheduleNextTrigger
    End If
End Sub

Public Sub StopTimer()
     If timerActive = True Then
        timerActive = False
        Application.OnTime nextTriggerTime, "Timer.OnTimer", Schedule:=False
    End If
End Sub

Private Sub ScheduleNextTrigger()
    If timerActive = True Then
        nextTriggerTime = Now + TimeValue("00:00:01")
        Application.OnTime nextTriggerTime, "Timer.OnTimer"
    End If
End Sub

Public Sub OnTimer()
    Call MainForm.OnTimer
    Call ScheduleNextTrigger
End Sub

これで、メインフォームから呼び出すことができます:

call Timer.StartTimer
call Timer.StopTimer

エラーを防ぐには、次を追加します。

Private Sub UserForm_Terminate()
    Call Timer.StopTimer
End Sub

これがトリガーされます:

Public Sub OnTimer()
    Debug.Print "Tick"
End Sub
于 2017-07-10T03:10:05.847 に答える