Loop through range and set values - javascript

I would like to create a loop that goes through the range A1:A150 and sets the cell value to =readmessage(Sheet2!A1) with A1 changing dynamically with each cell. So with A2 it reads, Sheet2! A1.
function storeValue() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:A150");
for (var i = 1; i < range.length; i++) {
range.setValue("=readMessage(Sheet2!"+range+")");
}
}
This doesn't work, nothing is written into the cells in the range.
I'm guessing it's something to do with range.setValue.

Don't confuse values with formulas. For values there is setValue(value) and for formulas there is setFormula(formula).
By the other hand var range = sheet.getRange("A1:A150"); assigns a Range object to the range variable. To get get it address use getA1Notation()

This should work if I understood you correctly:
function storeValue(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
for (var i = 1; i < 150; i++) {
range = sheet.getRange("A"+i);
range.setValue("=readMessage(Sheet2! A"+i+")");
} }
Otherwise comment below.

Related

Select Random cell that is not Blank

I am having a problem that my brain cannot figure out.
I have a script that I copied and modified that will Randomly select a cell that is not blank from reassign!A1:A10
in reassign Tab I have a Query that will filter another sheet if a checkbox is ticked
so in reassign!A1:A10 it will depend if how many checkbox are ticked
the output is it only selects the first cell which is A1
Script:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("reassign");
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var newValue = "";
for(var i = 0; i < values.length; i++) {
if(values[i][0] != "") {
newValue = values[i][0];
break;
}
}
sheet.getRange("B2").setValue(newValue);
}
I am running out of ideas. Sorry
Thanks in advance
I tried researching for solutions, but I really can't figure it out.
This Script selects randomly but sometimes it selects blank cells
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("reassign");
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var newValue = values[Math.floor(Math.random()*values.length)][0];
sheet.getRange("B2").setValue(newValue);
}
The explanation that you have provide is not clear to me at all. But perhaps this small change might make a difference.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("reassign");
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var newValue = "";
for(var i = 0; i < values.length; i++) {
if(values[i][0] !== "") {
newValue = values[i][0];
break;
}
}
sheet.getRange("B2").setValue(newValue);
}
Random Selection of non blank values:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("reassign");
var range = sheet.getRange("A1:A10");
var values = range.getValues().flat().filter(e => e);
sheet.getRange("B2").setValue(values[Math.floor(Math.random() * values.length)]);
}
I'm not at the PC right now, but you may try to add this line before var newValue.....:
values = values.filter(function (n) {return (n != "")})

Getting the last non-empty cell in a column

I have a script that is adding or substracting a value (picked up in M2 cell) in each cell of a selected range (I mean a range that I can select with the mouse) :
function moreLess() {
var ss = SpreadsheetApp.getActive();
var sel = ss.getSelection().getActiveRangeList().getRanges();
for (var i=0; i<sel.length; i++) {
var range = sel[i];
var values = range.getValues();
var number = SpreadsheetApp.getActive().getSheetByName("sommaire_redac").getRange('M2').getValue();
for (var j=0; j<values.length; j++) {
for (var k=0; k<values[0].length; k++) {
values[j][k] += number;
}
}
range.setValues(values);
}
}
This works. But instead of selecting all the cells in which I want add or substract a value, I would like to select only one cell, and have a script that would select a range from this selected cell to the last non-empty cell of the column.
For example, instead of selecting cells T30:T36 like this…
with the code I have today
… I would like to select only T30, like this…
with the code I'd like to have
… and then I would like the script to get the last non-empty cell of the column (T36) and select the range T30:T36.
I mean I would like to get exactly the same result by selecting only T30 cell, that I today obtain by selecting T30:T36.
Thanks !
Using your own script, you could add a second line between var ss and var sel like this:
var ss = SpreadsheetApp.getActive();
ss.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate()
var sel = ss.getSelection().getActiveRangeList().getRanges();
It will select the remaining rows of that column ;)
This script helps you to find the last empty row of a column.
function lastEmpty(col) {
const sss = SpreadsheetApp.getActiveSpreadsheet();
const ss = sss.getActiveSheet();
const getlastEmptyRow = (colValues) => {
return colValues.length - colValues.reverse().findIndex(row => !!row[0]);
}
const colValues = ss.getRange(col+":"+col).getValues();
const lastEmptyRow = getlastEmptyRow(colValues);
return lastEmptyRow;
}
console.log(`last empty row in column T is ${lastEmpty('T')}`)

Google scripts: How to put a range in setValue

I have used the example code from this link, to make the code below.
https://yagisanatode.com/2017/12/13/google-apps-script-iterating-through-ranges-in-sheets-the-right-and-wrong-way/
Most of the code is working as expected, except for the last row.
In Column E, I want to place the custom function =apiav() with the data from cell A.
However the code is returning =apiav(Range) in the Google sheet cells. (to be clear it should be something like =apiav(a1))
I tried everything i could think of and of course googled for hours, but i am really lost and can't find the right solution for this.
function energy(){
var sector = "Energy";
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = 2;
var lastRow = 999 ;
var sheet = ss.getSheets()[0];
var searchRange = sheet.getRange(2,2, lastRow-1 ,1 );
var ouputrange = sheet.getRange(2,4, lastRow-1 ,1 );
//clear range first
ouputrange.clear("D:D");
ouputrange.clear("E:E");
/*
GOOD - Create a client-side array of the relevant data
*/
// Get array of values in the search Range
var rangeValues = searchRange.getValues();
// Loop through array and if condition met, add relevant
// background color.
for ( i = 0; i < lastColumn - 1; i++){
for ( j = 0 ; j < lastRow - 1; j++){
if(rangeValues[j][i] === sector){
sheet.getRange(j+2,i+4).setValue("yes");
var formularange = sheet.getRange (j+2,i+1);
sheet.getRange(j+2,i+5).setValue('=apiav(' + formularange + ')');
}
};
};
};
Replace:
var formularange = sheet.getRange(j+2,i+1);
with:
var formularange = sheet.getRange(j+2,i+1).getA1Notation();
So you will be able to pass the cell reference instead of the range object.

I need to redefine script on Google Sheets

I need help with this script. Basically is working, but running on the same ranges for the whole sheets ("A4:V50") and I need it to run different ranges in each sheet.
Thanks!
function clearIPs() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var i = 0; i < 46; i++) {
var sheet = allsheets[i]
sheet.getRange("A4:V50").clearContent();
}
}
Create some type of Settings Objects. For example:
var Settings = {
Sheet1 : "A4:V50",
Sheet2 : "A4:B20"
}
And then in your code you can use this information like so:
for (var i = 0; i < 46; i++) {
var sheet = allsheets[i];
// lets get the right settings for that sheet
var sheetNumber = i + 1;
var range = Settings["Sheet" + sheetNumber];
// if there is no value for that sheet, lets add a default
if( !range ){
range = "A1:B20";
}
// now we can use that reference
sheet.getRange( range ).clearContent();
}

Google Apps Script Taking one random cell from each row

So I have a sheet as seen here.
https://docs.google.com/spreadsheets/d/1r2ogg1ldR0CFjOJ6mVObY-WRVipJx_X3pQ0yM2HYEog/edit?usp=sharing.
I am trying to write a script that goes through every row in range A1:D and chooses one random cell to put in the F column of the same row.
I am new to GAP so Im not sure how to write the exact script for that. This is what I got so far
function random() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ss = sss.getSheetByName('Sheet1'); //the sheet that has the data
var range = ss.getRange('A1:D'); //the range I need
var data = range.getValues();
for(var i = ; i < data1.length; i++) { //at this point im just guessing based on online codes
= Math.floor(Math.random()*(j+1)); //method of randomization
ss.getRange('the i row of F column').setValue(data[i][1]); //choosing the row that is being used, selecting the first item of the shuffled array
};
}
You've been pretty close to the solution:
function random() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ss = sss.getSheetByName('Sheet1'); //the sheet that has the data
var range = ss.getRange(1,1,ss.getLastRow(), 4); //the range you need: 4 columns on all row which are available
var data = range.getValues();
for(var i = 0; i < data.length; i++)
{
var j = Math.floor(Math.random()*(data[i].length)); //method of randomization
var element = data[i][j]; // The element which is randomizely choose
ss.getRange(i+1, 6).setValue(element);
}
}
I've made some modification on your orignal code:
getLastRow() get the position of the last row which is use. Otherwise, you collect a array the size of your entire sheet.
The Math.random() function is multiply by the size of a row, so you can have as much column as you want.

Categories

Resources