Why doesn't copyTo(… PASTE_VALUES) work in the middle of a macro?

前端 未结 2 958
遇见更好的自我
遇见更好的自我 2021-01-15 04:57

One of my longstanding techniques with spreadsheets is Copy / Paste Special Values (C/PSV), in place. Having used formulas to produce the values I\'m interested in, I C/PSV

相关标签:
2条回答
  • 2021-01-15 05:06

    Confronted to a similar issue (e.g. copying the result of a calculation from one range of cells into another range in which I needed the result alone without the formulas), using {contentsOnly:true} instead of SpreadsheetApp.CopyPasteType.PASTE_VALUES did the job.

    0 讨论(0)
  • 2021-01-15 05:08

    SpreadsheetApp.flush() is likely the missing step in your macro. Basically, Apps Script optimizes reads & writes internally, and if you don't call this method, it is free to do things its way.

    Adding this where you currently separate your task into "Macro 1" and "Macro 2" should resolve the issue:

    ...
      spreadsheet.getCurrentCell().offset(0, 0, 1, 5).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
      // Force formulas to calculate and pending writes to be written.
      SpreadsheetApp.flush();
      // Read formula results and save as values.
      var keepers = spreadsheet.getRange('G:J');
    ...
    

    An additional method would be to condense your scripts from the "transactional" approach of a recorded macro, to the batch / efficient "big picture" view, by using setValues() instead of copyTo:

    ...
      SpreadsheetApp.flush();
      var toKeep = spreadsheet.getRange('G:J');
      toKeep.setValues(toKeep.getValues());
      toKeep.getSheet().deleteColumns(1, toKeep.getColumn() - 1);
    }
    

    Note that you still want the call to .flush().

    0 讨论(0)
提交回复
热议问题