Search code examples
google-sheetsgoogle-apps-script

Display pasted cells temporarily then return to main page


Im working in a type of basic POS system on Google Sheets and using AppScript to copy data but i want to display the pasted cells just for a second, as a kind of confirmation before returning to the input page:

function input() {
  const sh = SpreadsheetApp.getActiveSpreadsheet();
  const page = sh.getSheetByName("INPUT INGRESOS");
  const row = page.getRange("B9:B").getValues();
  const lastRow = row.filter(String).length;
  const output = sh.getSheetByName("BD INPUT")
  const data = page.getRange(9,1,lastRow,14).getValues();

  output.getRange(output.getLastRow()+1,1,lastRow,14).setValues(data).setBorder(true,true,true,true,true,true).activate();

  page.getRange(9,1,lastRow,13).clearContent();

  Utilities.sleep(3000);

  page.activate()
}

I tried using Utilitie.sleep in between the activation of the pages but it didn't work.


Solution

  • The real problem here is this:

    Spreadsheet operations are sometimes bundled together to improve performance, such as when doing multiple calls to Range.getValue().

    That means that your operations are not applied in order. It is not that Utilities.sleep() isn't working: rather, it does make the script wait, but for nothing, since all the changes are carried out after the sleep() timeout.

    What you need to do is make sure that the operations you want to do before pausing the script are indeed enforced at that moment, using SpreadsheetApp.flush():

    function input() {
      const sh = SpreadsheetApp.getActiveSpreadsheet();
      const page = sh.getSheetByName("INPUT INGRESOS");
      const row = page.getRange("B9:B").getValues();
      const lastRow = row.filter(String).length;
      const output = sh.getSheetByName("BD INPUT")
      const data = page.getRange(9,1,lastRow,14).getValues();
    
      output.getRange(output.getLastRow()+1,1,lastRow,14)
            .setValues(data)
            .setBorder(true,true,true,true,true,true)
            .activate();
    
      page.getRange(9,1,lastRow,13).clearContent();
    
      SpreadsheetApp.flush();  // <-- This line makes the difference.
    
      Utilities.sleep(3000);
    
      page.activate()
    }
    

    You can also add, as @Aras Bulak suggested, the cells' highlighting if you wish for a nice touch ;)