Say I have an integer value "45,678.25" in cell A10 in google sheet.
Initially, I will use below command to assign the value in A10 into a variable:
Method1:
var myitem=sheet.getRange(10,1).getValue();
Then I noticed that I could also do the same with below command:
Method2:
var sheetdata=sheet.getDataRange().getValues();
var myitem=sheetdata[9][0];
I plan to change all from method 1 (getValue) to method 2 (calling by value position in DataRange) in all of my custom functions as I feel it looks tidier. But is it safe to do so? Will there be any impact on the end result/output?
I've created sampling test code with the output to show that there IS a significant impact to the output.
Sampling Code with Method 1 :
function checker(){
var ss=SpreadsheetApp.openById('SHEET_ID').getSheetByName('mystaff'),
staffdata=ss.getDataRange().getValues(),
lastrow=ss.getLastRow(),
staffID=ss.getRange(lastrow,1).getValue(),
name=ss.getRange(lastrow,4).getValue(); // Marlina
ss.getRange(lastrow,2).setFormula('=COUNTIF($D1:D'+lastrow+',D'+lastrow+')') // 2
ss.getRange("mystaff!B"+lastrow+":B"+lastrow).copyTo(ss.getRange("mystaff!B"+lastrow), {contentsOnly: true});
//Method 1
var RFQ=ss.getRange(lastrow,2).getValue();
console.log("RFQ by getValue:"+RFQ); // 2
//end of Method 1
if(staffID==""){
if(RFQ>1){
staffID=name.slice(0,3).toUpperCase();
console.log("moreRFQ :"+RFQ);
staffID=staffID+'('+RFQ+')';
Logger.log("newstaffID : "+staffID);
}else{
staffID=name.slice(3,5).toUpperCase();
console.log("firstRFQ :"+RFQ);
staffID=staffID+'('+RFQ+')';
Logger.log("newstaffID : "+staffID);
}
}
ss.getRange(lastrow,1).setValue(staffID); // output : MAR(2)
}
Sampling Code with Method 2:
function checker(){
var ss=SpreadsheetApp.openById('SHEET_ID').getSheetByName('mystaff'),
staffdata=ss.getDataRange().getValues(),
lastrow=ss.getLastRow(),
staffID=ss.getRange(lastrow,1).getValue(),
name=ss.getRange(lastrow,4).getValue(); // Marlina
ss.getRange(lastrow,2).setFormula('=COUNTIF($D1:D'+lastrow+',D'+lastrow+')') // 2
ss.getRange("mystaff!B"+lastrow+":B"+lastrow).copyTo(ss.getRange("mystaff!B"+lastrow), {contentsOnly: true});
//Method 2
var RFQ=staffdata[lastrow-1][1];
console.log("RFQ by array:"+RFQ); // blank
//end of Method 2
if(staffID==""){
if(RFQ>1){
staffID=name.slice(0,3).toUpperCase();
console.log("moreRFQ :"+RFQ);
staffID=staffID+'('+RFQ+')';
Logger.log("newstaffID : "+staffID);
}else{
staffID=name.slice(3,5).toUpperCase();
console.log("firstRFQ :"+RFQ);
staffID=staffID+'('+RFQ+')';
Logger.log("newstaffID : "+staffID);
}
}
ss.getRange(lastrow,1).setValue(staffID); // output : LI()
}
The different output is literally caused by the different subfunction it runs based on the IF..ELSE result, although the input source is the same. I'm so curious of why this could happen? Appreciate some logic explanation. Thanks.