工作簿,保存,关闭,重新打开(带TimeValue),重复

时间:2019-01-19 19:36:40

标签: excel vba time rtd ontime

该宏通过分配给“ CloseMe”的按钮运行。它曾经可以满足我的需求,但现在不再运行(因为我尝试在另一个工作簿中使用此代码而没有成功)。现在,它保存,关闭,等待10秒重新打开,然后立即关闭。

Sub CloseMe()
Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
ThisWorkbook.Close True
End Sub

Sub OpenMe()
Application.OnTime Now + TimeValue("00:10:00"), "OpenMe"
ThisWorkbook.Close True
End Sub

我需要代码来保存,关闭,等待10秒重新打开,保持打开状态10分钟(以收集实时数据),然后重复此过程(直到我手动中断以停止操作)。谢谢

3 个答案:

答案 0 :(得分:1)

该代码执行了您要执行的操作: CloseMe从现在开始计划OpenMe 10秒钟,然后关闭工作簿,然后关闭b。 Excel重新打开工作簿并调用OpenMe,该计划从现在开始将自身安排10分钟,然后立即继续关闭工作簿,最后Excel在10分钟后在b中恢复循环。

我的理解是,您的代码必须在OpenMeCloseMe中执行某些操作,因此您不想仅安排呼叫并关闭工作簿。此外,要进行循环,一个子需要安排另一个子。概括地说,您可以遵循以下原则:

Sub CloseMe()
    'Here, do whatever (if anything) must be done just before saving the workbook.
    '...

    'Schedule the OpenMe execution in 10 seconds.
    'I don't understand why you need to close the workbook, but that's not the question.
    Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
    ThisWorkbook.Close True
End Sub

Sub OpenMe()
    'Here, do whatever (if anything) must be done just as the workbook opens.
    '...

    'Schedule the CloseMe execution in 10 minutes.
    Application.OnTime Now + TimeValue("00:10:00"), "CloseMe"
End Sub

答案 1 :(得分:0)

您正在为Open和Close子对象调用OpenMe子对象。

如果您希望它自动运行,除了命令按钮以外,在何处调用close sub?

答案 2 :(得分:0)

@Excelosaurus我们非常接近。感谢您在不同的子代码上进行逻辑解释。这是完整的代码。它可以正常工作,但是在录制,关闭和重新打开时,我的时间戳加倍。我正在捕获一些RTD,为了使RTD刷新,您需要打开和关闭工作簿。我尝试在ActiveWorkbook.ForceFullCalculation = True中插入以避免多余的打开/关闭子,但是RTD并没有使用此方法重新计算,因此唯一的方法是运行打开/关闭子。

Dim NextTime As Double
Sub RecordData()
Dim Interval As Double
Dim cel As Range, Capture As Range
Application.StatusBar = "Recording Started"
Set Capture = Worksheets("Dashboard").Range("C5:K5") 'Capture this row of data
With Worksheets("Journal") 'Record the data on this worksheet
Set cel = .Range("A2") 'First timestamp goes here
Set cel = .Cells(.Rows.Count, cel.Column).End(xlUp).Offset(1, 0)
cel.Value = Now
cel.Offset(0, 1).Resize(1, Capture.Cells.Count).Value = Capture.Value
End With
NextTime = Now + TimeValue("00:01:00")
Application.OnTime NextTime, "RecordData"
End Sub

Sub StopRecordingData()
Application.StatusBar = "Recording Stopped"
On Error Resume Next
Application.OnTime NextTime, "OpenMe", , False
On Error GoTo 0
End Sub

Sub OpenMe()
Call RecordData
Application.OnTime Now + TimeValue("00:10:00"), "CloseMe"
End Sub

Sub CloseMe()
Application.OnTime Now + TimeValue("00:00:10"), "OpenMe"
ThisWorkbook.Close True
End Sub