For loop incrementing other variable too many times - javascript

Context: I'm making a script for Sheets that will colour an internal Sheets calendar to show start and end dates based on filling in a task's details elsewhere in the Sheet.
Bizarre situation: For each increasing column I set the start date from, colCount is incremented an extra time (more than I want), as shown in the pictures attached. The colCount keeps track of how many cells should be painted blue (finishing at the cell before end date)
http://i.imgur.com/2kNGTIG.png - Sheet 1 with task details
http://i.imgur.com/KhNBi4Q.png - Sheet 2 with calendar, showing where the painting occurs
Why is colCount being incremented too many times?
for (var k = 2; k < 100; k++){ //iterate over rows (searching tasks)
if (ss2.getRange(k, 1).getValue() === task){ //check correct row for task
var colCount = 1;
var start;
for (var i = 2; i < 100; i++){ //iterate over columns (searching dates)
var dateCell = ss2.getRange(1, i).getValue().getTime(); //this is cell that has date
if (dateCell == startDate){
start = i; //set column where start date is
}
else if (dateCell != endDate && dateCell != startDate){
colCount++;
}
else if (dateCell == endDate){
e.range.setNote("4.5: - start " + start + " - colCount " + colCount);
ss2.getRange(k, start, 1, colCount).setBackground("#4d79ff"); //set blue
ss2.getRange(k, i).setBackground("#fe4343"); //set red, working fine
return;
}
}
}
}
Edit: found an alternative way of achieving what I wanted. I just used the line
var cols = ss2.getRange(1, i).getColumn() - start;
to get the number of columns to paint, then use cols instead of colCount.

I think your problem might be in the line
var dateCell = ss2.getRange(1, i).getValue().getTime();
Shouldn't you be getting the range (k,i) since you're on row k?

Related

Google apps script - Why isn't my for-loop executing?

I'm trying to write a simple script to clear the values from a specific Google Sheets range [H29:H] if the background color of the cell = #ffff00. While the script doesn't return any errors, it isn't making any changes to cells that meet those criteria (or anywhere else in the sheet). Any guidance as to where I am going wrong?
function resetCells() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Test Sheet');
var rangeData = sheet.getDataRange();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange('H29:H');
var rangeColors = searchRange.getBackgrounds();
for ( i = 29 ; i < lastRow - 1; i++){
if(rangeColors[i][8] === '#ffff00'){
sheet.getRange(i,8).clearContent();
};
};
}
When I saw your script, I thought that the index of rangeColors might not be corresponding to i in the for a loop. I thought that this might be the reason for your issue. In this case, how about the following modification?
Modified script:
From:
for ( i = 29 ; i < lastRow - 1; i++){
if(rangeColors[i][8] === '#ffff00'){
sheet.getRange(i,8).clearContent();
};
};
To:
for (i = 0; i < rangeColors.length; i++) {
if (rangeColors[i][0] === '#ffff00') {
sheet.getRange(i + 29, 8).clearContent();
}
}
or, in your situation, when sheet.getRange(i + 29, 8).clearContent() is used at outside of the loop, the process cost might be able to be reduced a little. In this case, please modify as follows.
var rangeList = rangeColors.reduce((ar, [h], i) => {
if (h === '#ffff00') ar.push("H" + (i + 29));
return ar;
}, []);
sheet.getRangeList(rangeList).clearContent();
In this modification, when the background color of the cell of column "H" is #ffff00, the cell content is clear.
Reference:
Class RangeList
What you did wrong
In rangeColors[i][8] you were assuming rangeColors related to the cells in the spreadsheet. But they actually relate to the searchRange you made. So rangeColors[i][8]should be rangeColors[i][0]. Where i starts at 0.
To make it "extra fun" for you rangeColors is an array which is zero-based indexed. And when you are working with a range you can retreive the first cell with range.getCell(1, 1), not range.getCell(0, 0).
Because I got a little carried away I wrote this solution ( may be an interesting extra to read )
I don't think mapping an array of arrays (rangeColors) to a range is a great way to do this; It's hard to keep track on what your code is doing.
What I did was:
Create a range to check
Generate column and row numbers for all the cells in the range. Note that these are relative to the range, not the stylesheet. So range.getCell(1, 1) is the top left cell in the range. This is the (main) mistake you made in your code.
Do whatever you want with every individual cell in the range.
code:
resetCells( '#ffff00' );
function resetCells( color ) {
const app= SpreadsheetApp.getActiveSpreadsheet();
const sheet = app.getSheetByName('Sheet1');
const range = sheet.getRange('F4:F50');
for( let row = 1; row < range.getNumRows() + 1; row++ ) {
for( let column = 1; column < range.getNumColumns() + 1; column++ ) {
const cell = range.getCell( row, column );
if( cell.getBackground() === color )
cell.clearContent();
}
}
}
Disclaimer: I never used this google-app-script before. So I may have done something wrong performance-wise; iterating a large amount of cells takes a little long;

How do I change a set range in a google sheets script so that it can be selected in the cell?

First off, I am not a coder at all, just a teacher who's handy at googling things to make life easier. In my attendance book, I bold the times a student comes in tardy (they get a 1 if present and a 0 if absent in order to calculate attendance rate).
I found an awesome script that allows me to count the number of bold items in a range. However, the range is set and I can't specify a new range within google sheets for each student as is necessary.
I tried changing it to "function countColoredCells(countRange)" but it doesn't work as I assume there is something else I have to do within the rest of the script.
I literally have little to no coding knowledge and would really appreciate any help to solve this!
function countboldcells() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var range_input = sheet.getRange("C3:S3");
var range_output = sheet.getRange("N3");
var cell_styles = range_input.getFontWeights();
var count = 0;
for(var r = 0; r < cell_styles.length; r++) {
for(var c = 0; c < cell_styles[0].length; c++) {
if(cell_styles[r][c] === "bold") {
count = count + 1;
}
}
}
range_output.setValue(count);
}
range_input in the existing script is hard-coded. This is unsatisfactory because it doesn't permit analysis on a student-by-student basis. To fix this, you need to loop through the data for each student, and do 'countbold' for each student.
Let's assume that "C3:S3" is the range for a single student. Let's also assume that the data for other students is contained in each subsequent row, and that there are two header rows.
To do:
Work out the number of rows of student data - refer variable ALast.
Get the data for all students in one go. Why? Because this is more efficient than getting the data one row at a time - refer range_input discussed below.
Loop through each row of the data (i.e. loop by student - using a "for" loop).
Count the bold cells and update the results for each student - using most of your existing code;
Note:
The destination range (range_output) is calculated for each row, using getRange (row,column). This could have been done by saving values to an array, and updating all the values in a single process, but I though it was better to retain the approach the OP had already taken, and not over-complicate matters. If there are a LOT of students AND the code is taking too long to run, then updating the counts by array would be more efficient.
The input range (range_input) is defined using getRange(row, column, numRows, numColumns).
row = 3, the first row of data
column = 3, Column C
numRows = a calculated value (ALast minus two header rows)
numColumns = Columns C to S inclusive = 17 (assigned to a variable).
function so54260768() {
// Setup spreadsheet and target sheet
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
// get the number of students in Column A
var Avals = book.getRange("A1:A").getValues(); // assuming rows one and two are headers
var Alast = Avals.filter(String).length;
//Logger.log("DEBUG: The last row on A = " + Alast);// DEBUG
// number of columns in the data range
var NumberofColumns = 17;
// get the data for all students
var range_input = sheet.getRange(3, 3, Alast - 2, NumberofColumns); // the first two rows are headers
var cell_styles = range_input.getFontWeights();
// start loop though each row - one row per student
for (z = 0; z < Alast - 2; z++) {
// set the bold counter to zero
var count = 0;
//loop through the cells in this row; count the cells that are bold
for (var i = 0; i < NumberofColumns; i++) {
if (cell_styles[z][i] === "bold") {
count = count + 1;
}
}
//Logger.log("DEBUG: row="+(z+3)+", count="+count);//DEBUG
var range_output = sheet.getRange(z + 3, 14).setValue(count); //. row, column
}
}

Optimizing Code - getValue() and looping

I'm a bit of newbie at coding, especially Javascript/Google-script language. I've created the code below, and it works, but now that I've got a working code I'd like to see how I can optimize it. It seems to me that all of the getValue() calls are a major performance hit, and I've never really been good at optimizing loops. Anyone know a better way to accomplish the same as this code?
What it does: Checks each spreadsheet in one of my folders to see if it needs to have the rest of the script run. If true, it opens that sheet and counts the number of rows that have data, using that to limit the amount of rows it checks in the loop. It then looks for any row marked for push and copies that range to another spreadsheet in my drive. It then continues to the next file in the folder and does the same.
Here's my code:
function myVupdate() {
try {
var folder = DriveApp.getFolderById("123abc"),
files = folder.getFiles();
while (files.hasNext()) {
var file = files.next(),
sss = SpreadsheetApp.open(file);
SpreadsheetApp.setActiveSpreadsheet(sss);
//Work orders update
var ss = sss.getSheetByName("Sheet2"),
refresh = ss.getRange("W3").getValue();
if (refresh == 0) {continue};
var avals = ss.getRange("D5:D").getValues(),
count = avals.filter(String).length,
rows = count + 5
var val = ss.getDataRange().getValues();
for (var row=5; row < rows; row++) {
var cell = ss.getDataRange().getCell(row, 23).getValue();
if (cell == 0) {
var cells = [["v" + "WO-" + val[row-1][3] + "_" + val[row-1][2],val[row-1][13],val[row-1][14],val[row-1][15],new Date()]];
var tss = SpreadsheetApp.openById("target_spreadsheet"),
ts = tss.getSheetByName("Sheet5");
ts.insertRowBefore(2);
var last_hmy = ts.getRange(3,1).getValue();
ts.getRange(2,1).setValue(last_hmy+1);
ts.getRange(2,2,cells.length,cells[0].length).setValues(cells);
ts.getRange(2,7).setValue(sss.getName());
ss.getRange(row,17).setValue(last_hmy+1);
ss.getRange(row,18,cells.length,cells[0].length).setValues(cells);
//Turnover update
var ss = sss.getSheetByName("Sheet1"),
avals = ss.getRange("D5:D").getValues(),
count = avals.filter(String).length,
rows = count + 5
var val = ss.getDataRange().getValues();
}
}
for (var row=5; row < rows; row++) {
var cell = ss.getDataRange().getCell(row, 24).getValue();
if (cell == 0) {
var cells = [["v" + val[row-1][3] + "_" + val[row-1][2],val[row-1][12],val[row-1][15],val[row-1][16],new Date()]];
var tss = SpreadsheetApp.openById("target_spreadsheet"),
ts = tss.getSheetByName("Sheet5");
ts.insertRowBefore(2);
var last_hmy = ts.getRange(3,1).getValue();
ts.getRange(2,1).setValue(last_hmy+1);
ts.getRange(2,2,cells.length,cells[0].length).setValues(cells);
ts.getRange(2,7).setValue(sss.getName());
ss.getRange(row,18).setValue(last_hmy+1);
ss.getRange(row,19,cells.length,cells[0].length).setValues(cells);
}
}
}
}
catch(e) {
// Browser.msgBox("An error occured. A log has been sent for review.");
var errorSheet = SpreadsheetApp.openById ("target_sheet").getSheetByName("Error Log"),
source = sss.getName();
lastRow = errorSheet.getLastRow();
var cell = errorSheet.getRange('A1');
cell.offset(lastRow, 0).setValue(e.message);
cell.offset(lastRow, 1).setValue(e.fileName);
cell.offset(lastRow, 2).setValue(e.lineNumber);
cell.offset(lastRow, 3).setValue(source);
cell.offset(lastRow, 4).setValue(new Date());
MailApp.sendEmail("my#email.com", "Error report - " + new Date(),
"\r\nSource: " + source + "\r\n"
+ "\r\nMessage: " + e.message
+ "\r\nFile: " + e.fileName
+ "\r\nLine: " + e.lineNumber
);
}
}
Hello and welcome to Stack Overflow,
first of all, you are correct. The more getValue(), or setValue() calls you do the worse the performance, read more on best practices here. Google recommends you batch these as much as possible. One thing that immediately springs to attention is the following:
var val = ss.getDataRange().getValues();
so now you have all the values on the sheet in a 2D array. That means that in the following bit
var ss = sss.getSheetByName("Sheet2"),
refresh = ss.getRange("W3").getValue();
if (refresh == 0) {continue};
var avals = ss.getRange("D5:D").getValues(),
count = avals.filter(String).length,
rows = count + 5
var val = ss.getDataRange().getValues();
for (var row=5; row < rows; row++) {
var cell = ss.getDataRange().getCell(row, 23).getValue();
every single getValue() or getValues() is no longer necessary. Instead, you know that refresh = val[2][22] because you need the 3rd row and 23rd column, as you already have the entire range that has data from that sheet.
Same with avals as all values in range D5:D are in vals[n][3], where n starts from 4. Remember, the array index starts from 0 (so first row and first column is vals[0][0].
So anywhere you are trying to use getValues() from the ss spreadsheet, you already have that data. What you can also do, is manipulate the array you have, so you always change the values only in that array. Once you are done with it, you use ss.getDataRange().setValues(vals) to push the entire array back to the same range (you can just store the range in a variable like datRange = ss.getDataRange() and then do datRange.setValues(vals).
You will just need to work with a separate data array for any other sheet. I did not go into detail for the rest of the code as the same ideas go throughout. Since you already grab everything with getValues() there is no longer any reason to use getValue() for any cell within that range.

JavaScript variable missing value

I'm making a google sheet that writes to a SQL server periodically. This is my code so far, less the SQL stuff. It grabs the a variable from the last entry in the database ("User" in this test), and submits everything after it.
function connectToMySqlDB() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var lastColumn = sheet.getLastColumn();
Logger.log('Starting query process... ');
// Connect to DB and get last entry
var lastline = "User"
Logger.log('Found serial number of last enter in SQL Database: ' + lastline);
// Find row of entry in goolge sheet
for (var i = 0; i < values.length; i++) {
var row = "";
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == lastline) {
row = [i+1]
Logger.log('Found serial number in row: ' + row);
}
}
}
// Get first unfilled row
var crange = sheet.getRange("C1:C").getValues();
var Clast = crange.filter(String).length;
Logger.log('Found last row in C: ' + Clast);
var cfin = [Clast - row]
Logger.log('Slection will be: ' + row + ' rows.');
// select rows from entry to last filled row
var selection = sheet.getRange(row,0,cfin,lastColumn)
// Submit rows line by line to DB (from last entry to first unfilled)
// Write one row of data to a table.
}
The error I get from the google error is:
The coordinates or dimensions of the range are invalid. (line 33, file "Code")
Using the debug tool, the variable "row" has no value. The log file however shows that it does work
[16-09-15 11:39:41:063 PDT] Starting query process...
[16-09-15 11:39:41:064 PDT] Found serial number of last enter in SQL Database: User
[16-09-15 11:39:41:067 PDT] Found serial number in row: 26
[16-09-15 11:39:41:157 PDT] Found last row in C: 37
[16-09-15 11:39:41:158 PDT] Selection will be: rows.
My guess is somehow "var cfin = [Clast - row]" is clearing the "row" variable. I can't figure out for the life of me how to get around this.
You seem to want row to be a number, but you're wrapping its calculation in square braces, giving you an array of one element long. Remove the square braces.
row = i+1;
(As an aside, you're declaring it as a string, wont make a difference but its better to not do that!)
After that, you're making the same mistake with cfin. Dont wrap it in square braces if you simply want a number
var cfin = Clast - row;
You may also have a problem if row is set by being found, but then the outer loop will reset that variable. You can get round this by breaking out of both loops:
var row = -1;
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == lastline) {
row = i+1
Logger.log('Found serial number in row: ' + row);
break;
}
}
if(row > -1) break;
}

Check date and edit adjacent cell in Google Sheet with Google Script

I'm attempting to write a script that will change the status (Current vs Expired) in an adjacent cell when looping over the cell values of a column containing dates if the date is equal to or less than today's date. The script needs to work on column N (dates) and modify column O (statuses) across ALL sheets in the spreadsheet. That is why I have the Sheets loop in there FYI.
Here is what I have so far and I just keep hitting walls.
It's currently throwing an error at the currentValue variable for being out of range.
//----------------------------------------------------
// Look at Dates and Change Status if expired (Automatically)
function checkDates() {
//For each sheet in the Spreadsheet
for(v in sheets){
//Find the last row that has content *-2 is because of a strange return I don't understand yet
var lastRow = sheets[v].getLastRow()-2;
//Get Dates Range (excluding empty cells)
var dateRange = sheets[v].getRange("N2:N"+lastRow);
//Get the number of Rows in the range
var numRows = dateRange.getNumRows();
//For loop for the number of rows with content
for(x = 0; x <= numRows; ++x){
// Value of cell in loop
var currentValue = dateRange.getCell(x,2).getValue();
Logger.log(currentValue);
// Row number in Range
var currentRow = dateRange.getRow(x);
// Get adjacent cell Range
var adjacentCell = sheets[v].getRange(currentRow,15);
// If the date is less than or equal to today
if(new Date(currentValue) <= d){
// Change adjancet cell to Expired
adjacentCell.setValue("Expired");
// Else adjance cell is Current
} else if(listofDates != ""){
adjacentCell.setValue("Current");
}
}
}
}
//-----------------------------------------------------
The reason for currentValue to be out of range is that the getCell(x, 2) function first parameter is the row number. Your row number starts at 0, x = 0. If you change x to start at 1 it should stop giving you the error that the currentValue variable is out of range.
for(x = 1; x <= numRows; ++x){ ...
You are also selecting 2 columns across but you only selected out of row "N", change getCell(x, 2) to getCell(x, 1).
var currentValue = dateRange.getCell(x,1).getValue();
As I mentioned before your data range is only over colmn "N", it can make it easier if you select both column "N" and "O", var dateRange = sheets[v].getRange("N2:O");
I modified the rest of your script a bit. It is not pretty but I do hope it helps you.
function checkDates() {
//For each sheet in the Spreadsheet
for(v in sheets){
var lastRow = sheets[v].getLastRow();
//Get Dates Range (excluding empty cells)
var dateRange = sheets[v].getRange(2, 14, (lastRow - 1), 2);
//Get the number of Rows in the range
var numRows = dateRange.getNumRows();
//For loop for the number of rows with content
for(x = 1; x <= numRows; ++x){
// Value of cell in loop
var currentValue = dateRange.getCell(x,1).getValue();
var adjacentCell = dateRange.getCell(x,2);
Logger.log(currentValue);
// If the date is less than or equal to today
if(new Date(currentValue) <= new Date()){
// Change adjancet cell to Expired
adjacentCell.setValue("Expired");
// Else adjance cell is Current
} else if(currentValue != ""){
adjacentCell.setValue("Current");
}
}
}
}

Categories