I know very little about VBA but I made a macro which runs every 15 minutes that just adds a new row to the worksheet which contains the values from the first row (which are rtd functions). The longer I have this running, the more memory excel uses and after 24 hours it is using 1gb+ of RAM. Is there anyway I can improve this or stop this from happening so I can run the code for days? Thanks
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
I assume, based on you explicit identification of the objects involved that the
Sub Store()
is in a general module. If not, make sure it is declaredPublic
and mod the call inSub b()
below appropriately.You need to separate the action from the recall. Place two subs in a general module (EDITED - I mixed them up earlier on):
Replace the
Application.OnTime Now + TimeValue("00:15:00"), "Store"
in yourSub Store()
withCall a
. That's it.The
OnTime
works when it is in a General module (not in an Object module, e.g. a Worksheet module). Also, it should call a sub in a General module (Insert --> Module). I just know this works (took me a while to figure this out long time ago). In addition, this arrangement allows the "Store" routine to finish running and VBA engine to clear out the memory it used to run the "Store".Still, do not just trust me (or yourself either): always test!
From earlier experiments I also found that the
Application.OnTime
is not supposed to call itself (it needs to call a separate procedure), and the recursion to be handled in a different wayTry these 2 versions:
V1 - Application.OnTime
V2 - Sleep API (Edited - Non recursive)
Sleep is using less CPU as well