How to give a time delay of less than one second in excel vba?

后端 未结 10 2160
孤街浪徒
孤街浪徒 2020-11-29 06:14

i want to repeat an event after a certain duration that is less than 1 second. I tried using the following code

Application.wait Now + TimeValue (\"00:00:01\         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 07:13

    Public Function CheckWholeNumber(Number As Double) As Boolean
        If Number - Fix(Number) = 0 Then
            CheckWholeNumber = True
        End If
    End Function
    
    Public Sub TimeDelay(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
        If CheckWholeNumber(Days) = False Then
            Hours = Hours + (Days - Fix(Days)) * 24
            Days = Fix(Days)
        End If
        If CheckWholeNumber(Hours) = False Then
            Minutes = Minutes + (Hours - Fix(Hours)) * 60
            Hours = Fix(Hours)
        End If
        If CheckWholeNumber(Minutes) = False Then
            Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
            Minutes = Fix(Minutes)
        End If
        If Seconds >= 60 Then
            Seconds = Seconds - 60
            Minutes = Minutes + 1
        End If
        If Minutes >= 60 Then
            Minutes = Minutes - 60
            Hours = Hours + 1
        End If
        If Hours >= 24 Then
            Hours = Hours - 24
            Days = Days + 1
        End If
        Application.Wait _
        ( _
            Now + _
            TimeSerial(Hours + Days * 24, Minutes, 0) + _
            Seconds * TimeSerial(0, 0, 1) _
        )
    End Sub
    

    example:

    call TimeDelay(1.9,23.9,59.9,59.9999999)
    

    hopy you enjoy.

    edit:

    here's one without any additional functions, for people who like it being faster

    Public Sub WaitTime(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
        If Days - Fix(Days) > 0 Then
            Hours = Hours + (Days - Fix(Days)) * 24
            Days = Fix(Days)
        End If
        If Hours - Fix(Hours) > 0 Then
            Minutes = Minutes + (Hours - Fix(Hours)) * 60
            Hours = Fix(Hours)
        End If
        If Minutes - Fix(Minutes) > 0 Then
            Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
            Minutes = Fix(Minutes)
        End If
        If Seconds >= 60 Then
            Seconds = Seconds - 60
            Minutes = Minutes + 1
        End If
        If Minutes >= 60 Then
            Minutes = Minutes - 60
            Hours = Hours + 1
        End If
        If Hours >= 24 Then
            Hours = Hours - 24
            Days = Days + 1
        End If
        Application.Wait _
        ( _
            Now + _
            TimeSerial(Hours + Days * 24, Minutes, 0) + _
            Seconds * TimeSerial(0, 0, 1) _
        )
    End Sub
    

提交回复
热议问题