Excel安排VBA在特定时间运行

时间:2017-03-23 14:09:48

标签: vba excel-vba timer excel

有一个VBA代码,每隔5秒就会将一些单元格保存到一个新行。我想每天早上7点到晚上8点运行这项任务。然后在晚上10点后删除单元格,以便我可以在第二天开始新的(删除范围B2:C10000)。感谢您的帮助。以下是我目前的宏:

Option Explicit
Public dTime As Date

Sub ValueStore()
    Dim RowNo As Long
    RowNo = Sheets("Data").Cells(Rows.Count, 3).End(xlUp).Row + 1

    Sheets("Data").Cells(RowNo, 2) = Sheets("GetData").Cells(2, 2).Value2
    Sheets("Data").Cells(RowNo, 3) = Sheets("GetData").Cells(2, 5).Value2    
    Call StartTimer
End Sub
Sub StartTimer()

    dTime = Now + TimeValue("00:00:05")
    Application.OnTime dTime, "ValueStore", Schedule:=True
End Sub

Sub StopTimer()
    On Error Resume Next
    Application.OnTime dTime, "ValueStore", Schedule:=False
End Sub

1 个答案:

答案 0 :(得分:0)

添加了一个循环子来运行不同的任务:

If hasRun = False Then
    Sheets("GetData").Range("H1").Value = "Running"
    dTime = Now + TimeValue("00:00:10")
    Application.OnTime dTime, "ValueStore", Schedule:=True

    Application.OnTime TimeValue(Sheets("GetData").Range("O1").Text), "StartTimer"
    Application.OnTime TimeValue(Sheets("GetData").Range("O2").Text), "StopTimer"
    Application.OnTime TimeValue(Sheets("GetData").Range("O3").Text), "DeleteData"
    hasRun = True
End If

End Sub