Search code examples
google-apps-scriptgoogle-sheetsgoogle-speech-api

Google sheets script works as a script, but not a web app?


Sorry if I'm missing something really obvious here, Google scripts aren't my strong suit.

I'd like to be able to find data in a cell and overwrite it from an another site. I was attempting to modify this answer:

function test(){
 var sh = SpreadsheetApp.getActiveSheet();
 var data = sh.getDataRange().getValues(); // read all data in the sheet
 for(n=0;n<data.length;++n){ // iterate row by row and examine data in column A
 if(data[n][0].toString().match('xyz')=='xyz'){ data[n][5] = 'YES'};// if column A contains 'xyz' then set value in index [5] (is column F)
 }
 Logger.log(data)
 sh.getRange(1,1,data.length,data[0].length).setValues(data); // write back to the sheet
 }

by 1) changing SpreadsheetApp.getActiveSheet(); to SpreadsheetApp.openById("1ZHFGKtY7AaAtdMN8D5V9f2WTf8t9ldOW2pZ5my1CKnE").getSheetByName("Sheet1");, and 2) wrapping it in a doGet() function, so it looks like this:

function doGet(e) {  
  var sh = SpreadsheetApp.openById("1ZHFGKtY7AaAtdMN8D5V9f2WTf8t9ldOW2pZ5my1CKnE").getSheetByName("Sheet1");
  var data = sh.getDataRange().getValues(); // read all data in the sheet

  for(n=0;n<data.length;++n){ // iterate row by row and examine data in column A
    if(data[n][0].toString().match('xyz')=='xyz'){ 
      data[n][5] = 'YES'
    }; // if column A contains 'xyz' then set value in index [5] (is column F)
    sh.getRange(1,1,data.length,data[0].length).setValues(data); // write back to the sheet
  }
}

The function works fine as a script, but as soon as I add it to doGet() nothing happens, even though I get a message saying the script has completed. What is it I'm missing? :\

EDIT: It seems to be working form the "Test web app for your latest code" option; but even if I create a new version it still doesn't work from the link.

EDIT2: So although I'm not 100% sure what the problem was, it seems to have had something to do with being signed in to multiple Google accounts and setting "Who has access to this app". Or possibly an older version of the script got cached somewhere. Either way it's working now. 😕


Solution

  • So although I'm not 100% sure what the problem was, it seems to have had something to do with being signed in to multiple Google accounts and setting "Who has access to this app". Or possibly an older version of the script got cached somewhere. Either way it's working now. 😕