简体   繁体   English

VBA-计时器功能,可逐步捕获经过的时间

[英]VBA- A Timer Function, with Step by Step Capturing the elapsed times

I was looking for a timer function that easily can be embedded in my coeds to show me how many seconds each step is taking. 我一直在寻找一种计时器功能,该功能可以轻松地嵌入到我的课本中,向我展示每个步骤需要多少秒。 I am doing this with a regular debug.print and several variables which made my code busy and also hard to do subtracting new timer from last recorded step was redundant as well. 我使用常规的debug.print和几个变量来执行此操作,这使我的代码变得繁忙,并且也很难从最后记录的步​​骤中减去新计时器,这也是多余的。 I am looking for a function to capture the time takes for each step and also finding out the total elapsed time from the first step. 我正在寻找一个函数来捕获每个步骤花费的时间,并且还从第一步中找出总经过的时间。

Here is what I developed for that purpose. 这是我为此目的开发的。 You have to declare a public object of "Scripting.Dictionary" type and also a long variable as ti. 您必须声明“ Scripting.Dictionary”类型的公共对象,并且还要将长变量声明为ti。

Late Binding: 后期绑定:

Public d As Object, ti as long

and in one you your procedures, prior to calling the function: 在调用该函数之前,先执行以下步骤:

Set d = CreateObject("Scripting.Dictionary")

Early Binding 早期绑定

You can use early binding if you have Microsoft Scripting Runtime already added to your library. 如果已将Microsoft脚本运行时添加到库中,则可以使用早期绑定。 Your declaration would be like below: 您的声明如下:

Dim d As New Scripting.Dictionary, ti as long

anyway here is the: 无论如何,这里是:

Function 功能

Title is a string as a reminder or tag of the stage/step in the code. 标题是一个字符串,用于提示或标记代码中的阶段/步骤。
Newstart should set TRUE, for the first instance of the function. 对于该函数的第一个实例,Newstart应该设置为TRUE。
NeedTotal should set true if you want total elapsed time up until that stage. 如果您希望到该阶段为止的总经过时间,NeedTotal应该设置为true。

Public Function gettimer(Optional ByVal Title As String, _
                     Optional ByVal Newstart As Boolean, _
                     Optional ByVal NeedTotal As Boolean)
If Newstart = True Or ti = 0 Then
    ti = 0
    d("T0") = Timer
    gettimer = ti & vbTab & vbTab & "0.00" & vbTab & vbTab & "Start @ " _
    & Format(Time, "h:mm:ss") & vbTab & Title
Else
    gettimer = ti & vbTab & vbTab & Format(Round(Timer - d("T" & ti - 1), 2), "0.00") _
    & vbTab & vbTab & Title
    d("T" & ti) = Timer
End If
If NeedTotal Then
    gettimer = gettimer & vbTab & vbTab & vbTab & "Time elapsed from the start = " _
    & vbTab & Round(d("T" & ti) - d("T0"), 4)
End If
ti = ti + 1
Debug.Print gettimer
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM