Countdown Timer Excel VBA - Code crashed excel

后端 未结 3 360
渐次进展
渐次进展 2021-01-28 14:16

Could someone offer an insight into why this crashes my excel, i cant seem to work it out. Im trying to learn VBA and need some advice.

sub timer()

    dim         


        
相关标签:
3条回答
  • 2021-01-28 14:34

    I'm sure you're not timing space shuttle launches or anything that critical. But if you want to make sure your countdown doesn't take longer than 30 seconds, you can use the Timer function. Here's an example.

    Sub NewTimer()
    
        Dim Start As Single
        Dim Cell As Range
        Dim CountDown As Date
    
        'Timer is the number of seconds since midnight.
        'Store timer at this point in a variable
        Start = Timer
    
        'Store A1 in a variable to make it easier to refer
        'to it later. Also, if the cell changes, you only
        'have to change it in one place
        Set Cell = Sheet1.Range("A1")
    
        'This is the starting value. Timeserial is a good
        'way to get a time
        CountDown = TimeSerial(0, 0, 30)
    
        'Set our cell to the starting value
        Cell.Value = CountDown
    
        'Keep executing this loop until A1 hits zero or
        'even falls slightly below zero
        Do While Cell.Value > 0
            'Update the cell. Timer - Start is the number of seconds
            'that have elapsed since we set Start.
            Cell.Value = CountDown - TimeSerial(0, 0, Timer - Start)
    
            'DoEvents release control ever so briefly to Windows. This
            'allows Windows to do stuff like update the screen. When you
            'have loops like this, your code appears frozen because it's
            'not letting Windows do anything (unless you have this line)
            DoEvents
        Loop
    
    End Sub
    
    0 讨论(0)
  • 2021-01-28 14:36

    This is the best way to do this.

    Try to use this code below:

    Sub Countup() 
    Dim CountDown As Date 
    CountDown = Now + TimeValue("00:00:01") 
    Application.OnTime CountDown, "Realcount" 
    End Sub
    
    Sub Realcount() 'Run this to count down your cell value
    Dim count As Range 
    Set count = [E1] 'Put the range that you want to count down
    count.Value = count.Value - TimeSerial(0, 0, 1) 
    If count <= 0 Then 
    MsgBox "Countdown complete." 
    Exit Sub 
    End If 
    Call Countup 
    End Sub
    
    0 讨论(0)
  • 2021-01-28 14:43

    If it just about count down every second, I guess there is another option to add a Timer functionality to Excel. Try searching for Application.OnTime function in Excel that enables us to have Timer in Excel. Related Article that explains how to add timer in Excel and make a macro run during that scheduled interval.

    0 讨论(0)
提交回复
热议问题