Search code examples
google-apps-scriptgoogle-sheetscopy-pastegoogle-sheets-macros

Copy and paste values in google sheet with macro dont work


When I paste values from a formula with macro in google sheet the cell show empty

I need to copy the result of =now but only with values, the problem is that don't copy anything, for the example, y write the =now formula in F2 and I need to copy only the values in D2

spreadsheet.getRange('F2').activate();
  spreadsheet.getCurrentCell().setFormula('=NOW()');
  spreadsheet.getRange('D2').activate();
  spreadsheet.getRange('F2').copyTo(spreadsheet.getActiveRange(), 
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

I need that paste values to save this moment if I copy the formula its update in every change and it is no valid for me


Solution

  • Try it this way:

    function macro1() {
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getActiveSheet();
      sh.getRange('F2').activate();
      sh.getCurrentCell().setFormula('=NOW()');
      SpreadsheetApp.flush();
      sh.getRange('D2').activate();
      sh.getRange('F2').copyTo(sh.getActiveRange(),SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    }