Search code examples
google-apps-scriptgoogle-sheetsgoogle-forms

Close an open spreadsheet


I have a Google form that opens a spreadsheet by Id then it fetches data rows from it. I am in a situation that sometimes when I open the spreadsheet to get rows, to doesn't seem to fetch my most recently inserted data row. In this case I want to disconnect from my current connection to the spreadsheet and reconnect with a brand new connection, hoping that the new connecting would return with the most recently inserted row. Following is my code:

var sheet = SpreadsheetApp.openById("google_spreadsheet_id").getSheets()[0];
var numOfDataRows = Number(sheet.getLastRow()) - Number(1);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var dataRows = sheet.getRange(2, 1, numOfDataRows, sheet.getLastColumn()).getValues();

My question is to reconnect and establish a brand new connection do I simply do:

var sheet = SpreadsheetApp.openById("google_spreadsheet_id").getSheets()[0];

Is there a method that close a open spreadsheet by Id?


Solution

  • There is no such thing as closing a spreadsheet, but there is a method SpreadsheetApp.flush() that can be used to ensure that any pending changes to the spreadsheet (such as row insertions) actually happen before code execution proceeds.

    Also, if your script is triggered by data submission to a form, it's better to retrieve the data directly from the event object, rather than from the spreadsheet in which it may or may not appear yet.