Macro repeat at a time interval and works when spreadsheet is minimized

100 Views Asked by At

I wrote the below VBA. It is working but have the following problem. Any help would be appreciated. Problem:

  1. It does not paste exactly at the time interval assigned.
  2. It stops working when the spreadsheet is minimized - and gives error on Worksheets("IV track").Select.
    Sub CopyPaste()
    '
    '   Workbooks("Option Chain.xlsm").Activate
        Worksheets("IV track").Select
        Range("A14").Select
        Range(Selection, Selection.End(xlToRight)).Select
        Selection.Copy
        Range("A19").End(xlDown).Offset(1, 0).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Application.CutCopyMode = False
        Sheets("Nifty Analysis").Select
        Range("B4").Select
        Call Test
    End Sub
    
    Sub Test()
    Application.OnTime Now + TimeValue("00:15:00"), "CopyPaste"
    End Sub
1

There are 1 best solutions below

1
Rodentman87 On

The error when the Excel is minimized is caused because Worksheets(...) has an implied ActiveWorkbook. in front of it. When you minimize Excel, none of the workbooks are active, meaning that you are trying to grab the spreadsheet from an undefined workbook.

The reason that your macro doesn't run at exactly the right timing is that Application.OnTime is not meant to run things at exact times. If there is anything preventing Excel from running the macro, it will not run it immediately. The time you give it is the earliest time that it will run the macro, not a guaranteed time.