当使用application.ontime反复运行macros时,Excel使用太多的内存

我对VBA知之甚less,但是我做了一个每15分钟运行一次的macros,它只是在包含第一行(这是rtd函数)的值的工作表中添加一个新行。 我运行的时间越长,excel使用的内存越多,24小时后它使用的是1gb +的RAM。 有无论如何,我可以改善这一点,或阻止这种情况发生,所以我可以运行代码几天? 谢谢

Sub Store() currow = Workbooks("Store data.xlsm").Worksheets("Sheet1").Range("A65536").End(xlUp).Row Workbooks("Store data.xlsm").Worksheets("Sheet1").Cells(currow + 1, 1) = Format(Now, "dd/mm/yyyy HH:nn:ss") Workbooks("Store data.xlsm").Worksheets("Sheet1"). _ Range(Workbooks("Store data.xlsm").Worksheets("Sheet1").Cells(currow + 1, 2), _ Workbooks("Store data.xlsm").Worksheets("Sheet1").Cells(currow + 1, 47)) = _ Workbooks("Store data.xlsm").Worksheets("Sheet1"). _ Range(Workbooks("Store data.xlsm").Worksheets("Sheet1").Cells(2, 2), _ Workbooks("Store data.xlsm").Worksheets("Sheet1").Cells(2, 47)).Value Application.OnTime Now + TimeValue("00:15:00"), "Store" End Sub 

从以前的实验中,我也发现Application.OnTime不应该自己调用(它需要调用一个单独的过程),并且以不同的方式处理recursion

试试这两个版本:


V1 – Application.OnTime


 Option Explicit Public Sub UpdateStore() Application.OnTime Now + TimeValue("00:15:00"), "Store" End Sub Public Sub Store() Dim curRow As Long, firstRow As Range, lastRow As Range With Workbooks("Store data.xlsm").Worksheets("Sheet1") curRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1 .Cells(curRow, 1) = Format(Now, "dd/mm/yyyy HH:nn:ss") Set firstRow = .Range(.Cells(2, 2), .Cells(2, 47)) Set lastRow = .Range(.Cells(curRow, 2), .Cells(curRow, 47)) End With lastRow = firstRow.Value UpdateStore 'recursive call End Sub 

V2 – 睡眠API(已编辑 – 非recursion)


 Option Explicit #If Win64 Then 'Win64=true, Win32=true, Win16= false Private Declare PtrSafe Sub Sleep Lib "Kernel32" (ByVal dwMilliseconds As Long) #ElseIf Win32 Then 'Win32=true, Win16=false Private Declare Sub Sleep Lib "Kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long) #End If Public Sub StoreSleepAPI() Dim curRow As Long, firstRow As Range, lastRow As Range, counter As Long For counter = 1 To 400 '<-- adjust this to "how many hours" * "4" ( times / hour) With Workbooks("Store data.xlsm").Worksheets("Sheet1") curRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1 .Cells(curRow, 1) = Format(Now, "dd/mm/yyyy HH:nn:ss") Set firstRow = .Range(.Cells(2, 2), .Cells(2, 47)) Set lastRow = .Range(.Cells(curRow, 2), .Cells(curRow, 47)) End With lastRow = firstRow.Value Sleep 900000 '1000 = 1 second, 900000 = 15 minutes DoEvents Next End Sub 

睡眠也使用较less的CPU

我假设,基于你的Sub Store()在一个通用模块中涉及的对象的明确标识。 如果不是,请确保它被声明为Public并在下面的Sub b()中适当调用调用。

您需要将该行动与召回分开。 在通用模块中放置两个子文件(EDITED – 我之前将它们混合在一起):

  Public Sub a() Application.OnTime Now + TimeValue("00:15:00"), "b" End Sub Public Sub b() Call Store End Sub 

Application.OnTime Now + TimeValue("00:15:00"), "Store"replace为您的Sub Store()中的Call a 。 而已。

当它在一个通用模块(不在一个对象模块,例如一个工作表模块)时OnTime工作。 另外,它应该调用通用模块(插入 – >模块)中的一个子。 我只知道这是有效的(花了很长时间才弄清楚)。 此外,这种安排允许“存储”例程完成运行,VBA引擎清除用于运行“存储”的内存。

不过,不要只相信我(或者你自己):总是testing!