setFormulas won't skip empty array elements, over-writes values - google-apps-script

Consider the code below: it sets values then sets functions across a range, however it overwrites the values that were set.
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("A1:B2");
var values = [["First","row"],["Second","row"]];
var formulas = [["=42",""],["","=77"]];
range.setValues(values);
range.setFormulas(formulas);
}
Why is it that setting an empty formula will overwrite any set value and vice versa? Wondering if there is a way to skip setting an individual array element. I have tried 'undefined' and 'null with no luck.
Having to get the ranges of specific areas that require formulas for values to prevent overwriting of data adds an extra layer complexity to the script I'm writing.
Thanks for reading!

I think the problem can be largely mitigated by the fact that setValues() can be used to set formulae.
var range = ss.getRange("A1:B2");
var values = range.getValues();
// process the array, eg values[0][0] = "=42";
range.setValues();

This certainly explains why setting values overwrites formulas, but wouldn't it be nicer if there were a way to getValuesandFormulas together into an array?
If (like me) you were distracted into getValues and getFormulas, realise that you can use copyTo between ranges to copy the overall contents!

Related

Changing info on a different sheet in the same spreadsheet

I have two ranges of equal size on different sheets in the same spreadsheet. I am trying to find a row (based off of user input) in the first sheet and then use that index to modify a table in the second sheet that counts how many times that certain index has been used before (to make a nice looking pie chart).
This code runs but will not produce results on the second sheet. I've gone through the debugging process and my best guess is that for some reason, my for in loop is not running through. Attached is my code that takes in the beforementioned index and attempts to perform the second half of my goal.
function acceptToEncounterChart(ghostrow) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(ss.getSheets()[1]);
ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Average Encounter Chart");
var range = sheet.getRange("B3:B14")
for(var i in range) {
if(ghostrow == i) {
var before = range[i][0].getValue()
range[i][0].setValue(before + 1);
}
}
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
};
Explanation:
I am not entirely sure what is your goal.
However, here is some fixes / improvements starting from the beginning:
You define 2 times the same variable ss with exactly the same value.
You don't need to set the active sheet, if your goal is to just get the sheet, therefore this line is redundant:
SpreadsheetApp.setActiveSheet(ss.getSheets()[1]);
Variable range is not an array but a range object. You can't index it and therefore you can't also use a for loop to iterate over a single object. For the same exact reason, the code inside the if statement is wrong, you can't index range. But you don't see any errors because the if statement evaluates to false.
In JavaScript and in many other programming languages, array indexes start from 0. Since your range starts from cell B3 or row 3, you need to use i+3 to match the data with the range.
For the same reason as the previous point, ghostrow is an index, not a row. The if statement compares an array index i with ghostrow, so ghostrow should not be confused with the actual sheet row. For example, if you choose ghostrow=5 then the current script will increment the value of the cell B8 (remember i+3) by 1.
Solution:
Here is a workable code snippet:
function acceptToEncounterChart(ghostrow) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Average Encounter Chart");
var data = sheet.getRange("B3:B14").getValues().flat();
data.forEach((v,i)=>{
if(ghostrow == i){
sheet.getRange(i+3,2).setValue(v+1)
}
});
ss.setActiveSheet(ss.getSheets()[0]);
}
Related:
Please explore the official google apps script documentation.

getRange outputting "Range" instead of values

So, I'm making a code that copies certain data from our EOD worksheet, and copy/pasting the data onto another sheet, which acts as a summary.
I've got most of the code already working, but running into trouble with the getRange output. It just shows "Range" in the cell instead of my input, which should all be numbers.
function myFunction() {
var source = [];
var destSheet = SpreadsheetApp.getActive().getSheetByName('SnapshotSpreadsheet');
var destRange = destSheet.getRange(destSheet.getLastRow()+1,2);
source.push(sheet.getRange('B20'));
source.push(sheet.getRange('E20:F20'));
source.push(sheet.getRange('H20'));
source.push(sheet.getRange ('J20:I20'));
source.push(sheet.getRange ('M18'));
source.push(sheet.getRange ('K20'));
source.push(insertDate());
destSheet.getRange(2,1,1,7).setValues([source]);
I've included just the portion that is causing the issue. I defined source as an array, and stored values into the array, then just called for them to be output on the next available line. Everything seems to be lining up alright, just the values are all "Range".
You need to use getValue() (if single cell) or getValues() (if multiple cells) to get the content of those ranges.
Cfr https://developers.google.com/apps-script/reference/spreadsheet/range#getValue()
You'll need to do .getValues() for it to return the values of the cells
var values = sheet.getRange('E20:F20').getValues();
This returns a Two Dimensional array of values, so you'll have to work around that in your code. For example the line of code I just wrote would be an array like
[[Value at E20, Value at F20]]
so in order to access the Value at E20, you would call values[0][0] or for Value at F20, - values[0][1]

Lost zero number when appendRow

When I use appendRow in Google Sheets, I lose the leading zero (when my data is a 'phone number), how can I keep it?
I tried getDataRange().setNumberFormat('#STRING#') before append but this did not work.
var rowdata = ["dinh","loc","09182734756"]
ws.appendRow(rowdata );
Here's an image of my current result:
Actually, setNumberFormat() works fine, but you need to apply it via setNumberFormat('#') or setNumberFormats([['#']]) (depends on whether you want to set it on one cell or on a custom Range).
Please, remember to set number formats before setting values to the target Range.
function testZero() {
var sh = SpreadsheetApp.getActiveSheet();
var v = ["dinh","loc","09182734756"]; //do not add the "'";
sh.appendRow(['']); //no need to do this step, it's an example;
var rng = sh.getRange(sh.getLastRow()+1,1,1,v.length);
rng.setNumberFormats([['#','#','#']]); //for test simplicity, set on Range you need to be of 0\d* pattern;
rng.setValues([v]);
}
UPD: credit goes to Tanaike - a more flexible (and less heavy) solution to accessing the last column needed is via the values Array length.

setFormulas to a new spreadsheets when created

I have been searching through question and example everywhere but I can not seem to find an answer. I need to set these formulas in the header row and columns AQ:1 to AV:1(AQ1:AV1).
["={"Hours:";ArrayFormula((IF(LEN(AE2:AE),((AF2:AF-AE2:AE)*24)+(((T2:T-S2:S)*24))+(((I2:I-H2:H)*24)),)))}",
"={"Rest Hours:";ArrayFormula((IF(LEN(AE2:AE),((M2:M)*24)+(((X2:X)*24))+(((AJ2:AJ)*24)),)))}",
"={"Rest Hours Wages:";ArrayFormula((IF(LEN(AE2:AE),(AI2:AI*(AJ2:AJ*24)+(L2:L*(M2:M*24)+(W2:W*(X2:X*24)))),)))}",
"={"Hours-RestHours:";ArrayFormula((IF(LEN(AE2:AE),((AQ2:AQ-AR2:AR)),)))}",
"={"Rate:";ArrayFormula((IF(LEN(AE2:AE),((E2:E+P2:P+AB2:AB)),)))}"],
and I need to put this into the second row of column AQ (AQ2).
["=ArrayFormula((IF(LEN(AE2:AE),((AT2:AT*AU2:AU)+AS2:AS),)))}"],
I keep getting this error message and I cannot save the script.
Missing ] after element list. (line 138, file "Code")
I think I know why but I need the headers to be titled with the correct text because I use the headers in other functions.
function setFormulas(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// This sets the formulas to be a row of sums, followed by a row of averages right below.
// The size of the two-dimensional array must match the size of the range.
var formulas = [
["={"Hours:";ArrayFormula((IF(LEN(AE2:AE),((AF2:AF-AE2:AE)*24)+(((T2:T-S2:S)*24))+(((I2:I-H2:H)*24)),)))}",
"={"Rest Hours:";ArrayFormula((IF(LEN(AE2:AE),((M2:M)*24)+(((X2:X)*24))+(((AJ2:AJ)*24)),)))}",
"={"Rest Hours Wages:";ArrayFormula((IF(LEN(AE2:AE),(AI2:AI*(AJ2:AJ*24)+(L2:L*(M2:M*24)+(W2:W*(X2:X*24)))),)))}",
"={"Hours-RestHours:";ArrayFormula((IF(LEN(AE2:AE),((AQ2:AQ-AR2:AR)),)))}",
"={"Rate:";ArrayFormula((IF(LEN(AE2:AE),((E2:E+P2:P+AB2:AB)),)))}",
"={"Wages:";ArrayFormula((IF(LEN(AE2:AE),((AT2:AT*AU2:AU)+AS2:AS),)))}"],
["=ArrayFormula((IF(LEN(AE2:AE),((AT2:AT*AU2:AU)+AS2:AS),)))}"],
];
var cell = sheet.getRange("AQ1:AW2");
cell.setFormulas(formulas);
}
Am I missing something or am I doing it completely wrong and need to find another way to do it. I also need to add the formulas to every sheet in the spreadsheet but I have not been able to test if it works. Thank you in advance for any help.
UPD:
It seems like double quotes are interfering here. To avoid this, you can use single quotes for formula enclosure and double quotes within formula, like this:
'={"Hours:";ArrayFormula((IF(LEN(AE2:AE),((AF2:AF-AE2:AE)*24)+(((T2:T-S2:S)*24))+(((I2:I-H2:H)*24)),)))}'
As mentioned in comments:
Arrays would expand so you are likely to need setting formulas in one row, like AQ1:AW1
Besides, if there's source data in columns AQ:AU (by the looks of formulas), setting array formulas in the same columns will most likely return error: Array result was not expanded because it would overwrite data in AQ18.
You seem to have an extra } at the end of the last formula
Try this and adjust to your needs:
function setFormulas(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// This sets the formulas to be a row of sums, followed by a row of averages right below.
// The size of the two-dimensional array must match the size of the range.
var formulas = [
['={"Hours:";ArrayFormula((IF(LEN(AE2:AE),((AF2:AF-AE2:AE)*24)+(((T2:T-S2:S)*24))+(((I2:I-H2:H)*24)),)))}',
'={"Rest Hours:";ArrayFormula((IF(LEN(AE2:AE),((M2:M)*24)+(((X2:X)*24))+(((AJ2:AJ)*24)),)))}',
'={"Rest Hours Wages:";ArrayFormula((IF(LEN(AE2:AE),(AI2:AI*(AJ2:AJ*24)+(L2:L*(M2:M*24)+(W2:W*(X2:X*24)))),)))}',
'={"Hours-RestHours:";ArrayFormula((IF(LEN(AE2:AE),((AQ2:AQ-AR2:AR)),)))}',
'={"Rate:";ArrayFormula((IF(LEN(AE2:AE),((E2:E+P2:P+AB2:AB)),)))}',
'={"Wages:";ArrayFormula((IF(LEN(AE2:AE),((AT2:AT*AU2:AU)+AS2:AS),)))}',
'=ArrayFormula((IF(LEN(AE2:AE),((AT2:AT*AU2:AU)+AS2:AS),)))']
];
var cell = sheet.getRange("AW1:BC1");
cell.setFormulas(formulas);
}

Google Sheet Custom Function Not Recaculating

Hi I have read about the caching issues with custom functions in Google Sheets, but I'm trying to understand why the following will successfully update if a cell is changed:
function doob(input){
return input * 2;
}
but this will not update:
function doob(input){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(input);
var values = range.getValues();
return values[0][0] * 2 ;
}
I need to get the range in order to use the .getBackgroundColor() of each cell.
Probably because in the first function you would pass the cellreference directly,
=doob(A1)
and in the script the value of that cell is used.
In the second, you would probably have to pass the range as string (since you want to get the backgroundcolors, so you are not after the values of that range, right ?)
=doob("A1:B8")
As you know, custom functions suffer from memoization. To work around that you could pass in the range a second time, without the quotation marks.
=doob("A1:B8", A1:B8)
That second paramater is a 'dummy' paramater as the script does nothing with it. BUT: any change in values in that range should make the custom function re-evaluate. However I don't know if that is gonna help you a lot if your final goal is to get the backgroundcolors.