全局变量为空,即使它们已在子 vba 中设置

Global variables are empty even though they've been set within a sub vba

试图在 VBA 中创建一个计时器。我的意图是能够在其他函数中调用 TimerStartTimerLapsTimerStop 来估计代码块完成所需的时间。但是我的全局变量为空时遇到问题。

Private starttime As Double   

Sub TimerStart()
    starttime = Timer
End Sub

Function TimerLaps() As Double
    TimerLaps = Timer - starttime
End Function

Function TimerStop() As Double
    i = starttime
    starttime = 0
    TimerStop = Round(Timer - i, 2)
End Function

Sub test()
    Call TimerStart

    MsgBox TimerStop()
End Sub

谢谢大家!

尝试:

Global starttime As Double 

在模块的顶部 (而不是 Private starttime As Double

编辑

Global starttime As Double

Sub test()
    Call TimerStart
    Application.Wait (Now + #12:00:02 AM#)
    MsgBox TimerStop()
End Sub

Sub TimerStart()
    starttime = Timer
End Sub

Function TimerStop() As Double
    Dim i As Double
    i = starttime
    starttime = 0
    TimerStop = Round(Timer - i, 2)
End Function

您可以通过两种方式使用:

Global starttime As Double 

Public starttime As Double 

使用其中之一代替 Private。主要区别是:

Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.)
Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.