Google app script: find first empty cell in a row - google-apps-script

Im learning Google app script while building a dashboard. I'm collecting data from several sheets. My goal is to see by how many rows each sheet grows every week. This gives me insight in how my business is doing.
I can get the length of all the sheets I want to check, however I cant find any code which helps me to find the first empty cell in a specific row. I want to place the length of each sheet there (in my dashboard datacollection sheet) to create a graphs later on.
What I have is:
var range = ss.getRange(2, 1, 1, 1000);
var waarden = range.getValues();
Logger.log(waarden);
var counter = 0
for (var j = 0; j < ss.getLastColumn(); j++) {
Logger.log(waarden[0][j]);
if (waarden[0][j] == ""){
break
} else {
counter++;
}
Logger.log(counter);
}
This works but I can't image this being the best solution (or quickest solution). Any tips in case my length goes beyond 1000 without me noticing it (although it would take a couple of years to do so in this case ;) )?! Why does getLastColumn() behave so much different than getLastRow()?
Thanks for helping me learn :)
*** edited I figured out I have to use if (waarden[0][j] === ""){ with three = otherwise if my sheet in the row that I use as a check has a length of 0 than this is also counted as empty with two =operators.

Try indexOf()
function firstEmptyCell () {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = ss.getRange(2, 1, 1, ss.getMaxColumns());
var waarden = range.getValues();
// Get the index of the first empty cell from the waarden array of values
var empty_cell = waarden[0].indexOf("");
Logger.log("The index of the first empty cell is: %s", empty_cell);
}
This will give you the column position of the empty cell starting from a 0 index. So if the returned index is 4, the column is "E".
edit: As for the getLastColumn() question; you could use getMaxColumns() instead. Updated code to get all columns in the sheet.

Related

How to apply get range in combination with i++

Today I have come with something that I have been trying for quite some time now, but due to time issues, I do finally have decided to seek help.
For starters, I have this table:
Name
Score year 1
Score year 2
Now, each name will have it´s own tablepages for various reasons not relevant for this, so this forces me to be a bit inventive.
I have already figured out how to automatically enter the sheets with this function:
function sheetnames() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=6; i<sheets.length ; i++) out.push( [ sheets[i].getName() ] )
return out
}
Now, What I want to know if, and if so how, one can use this to get the scores for each year once the sheet is made.
For sake of clarity, I will outline it this way.
I want the function to grab a bunch of values from any sheets that would be included in the function above automatically.
if I make the sheet Alex and 100+ and enter the values on these sheets, they should appear in this table.
Apologies if something is written erroneous, I am not an native English speaker.
Please feel free to ask questions for clarification.
So you have n Sheets, all with a name and they all have a score for k years next to each other in the first row?
Why are you starting at the 5th Sheet?
I never had anything to do with google services and what not, but after a look in their docs, I found a function that gets the content of an area:
getSheetValues(startRow, startColumn, numRows, numColumns)
It returns a two dimensional array of the Values. You should test if the columns are the first index or the second. The following code assumes an array of rows (column are the second index). Take everything with a chunk of salt, I know Javascript for like 2 weeks and just googled a bunch of stuff.
function sheetnames() {
var out = new Array();
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=6; i<sheets.length ; i++) { //if you want to start at the 5th sheet otherwise i=0
var columns = sheets[i].getLastColumn(); // gets the last column with content (the length)
var content = sheets[i].getSheetValues(0, 0, 1, columns)[0]; // get one row
var newRow = content.unshift(sheets[i].getName());
out.push(newRow);
}
return out
}

Google Sheets OnEdit script: copy value from specific columns

We are using Google sheets for tracking attendance. Previously, the teachers were entering P, T, or A (for present, tardy, absent) for each period. I would still like users to have the option to enter a value for each period in a week, however it would be a great time saver if they could enter one value for the whole day.
What I'd like is that if a value is entered into any one of the "0" periods (green columns) with a "P" or "A" (data validation limits those options) an OnEdit function would copy that same letter ("P" or "A") to the following 8 columns and then delete the original value. (without the deletion the totals on the far right columns will be off). I would not want the OnEdit to be activitated based on edits in any of the non-green columns.
I will eventually have several tabs, each one a different week, but each exactly the same... so I'm thinking the function should work within whatever the activesheet is.
https://docs.google.com/spreadsheets/d/1NKIdNY4k66r0zhJeFv8jYYoIwuTq0tCWlWin5GO_YtM/edit?usp=sharing
Thank you for your help,
I wrote some code to get you started with your project. (I am also a teacher) You will have to make some changes based on what you are going for and it can probably be optimised to run faster. Good luck!
function onEdit(e) {
//create an array of the columns that will be affected
var allColumns = [2, 10];
//get the number values of the column and row
var col = e.range.getColumn();
var row = e.range.getRow();
//get the A1 notation of the editted cell for clearing it out
var cell = e.range.getA1Notation();
//only run if the cell is in a column in the allColumns array
if(allColumns.indexOf(col) > -1) {
//run the for loop for the next 8 cells
for(var i = col + 1; i < col + 9; i++) {
SpreadsheetApp.getActiveSheet().getRange(row, i).setValue(e.value);
SpreadsheetApp.getActiveSheet().getRange(cell).setValue('');
}
}
}

Very strange Google Apps Script behavior

I am seeing some very strange behavior with Google Apps Script. All I am trying to do is parse some rows in my sheet and if for any row, if the date is > 1/1/1999 then add a dropdown which pre populates some Error Value. The strange behavior here is that this always populates the dropdown one row above the row which satisfies the date check condition. So for example if row #5 satisfies the condition, the dropdown is populated in row #4. Not sure why this is happening. I also tried to do this
var range = sheet.getRange(i+1, 14);
but that doesn't seem to show anything on the screen. I am unable to understand this strange behavior. Any help will be appreciated.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
var dataRange = sheet.getDataRange();
var values = dataRange.getDisplayValues();
for (var i = rowNum; i < values.length; i++) {
if (new Date(values[i][9]).getTime() > new Date('1/1/1999').getTime()){
SpreadsheetApp.getUi().alert(values[i][2]);
var range = sheet.getRange(i, 14);
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['Error Value'], true).build();
range.setDataValidation(rule);
}
Use
var range = sheet.getRange(Number(i)+1, 14);
When you are using i+1 and when i=20, i+1 will become 201 and you will not seeing any visible difference on the screen. row 201 will be far down your screen.
In JavaScript, numbers and strings will occasionally behave in ways you might not expect. It is always good to take precaution before doing operation on variables.
Also read https://autotelicum.github.io/Smooth-CoffeeScript/literate/js-intro.html#operations-on-numbers-strings
Your data validation is set to null. It should be Range.setDataValidation(rule)
that is why you dont see a dropdown box.
This function
Range.getDisplayValues()
Returns an array and index of an array starts at 0. However, in a spreadsheet the row index starts at 1. So you need to add 1 to convert array index to a row index. Use the following to get the correct range
Sheet.getRange(i+1,14)

Autofill google forms based on user input

Alright stack friends,
I'm working on my first projects using google scripts and it's been pretty fun so far. My project is to create a form for data entry that can either accept an ID number and fill in the rest of the fields, or let the user fill out the entire form. Basically my method to fill in the other fields is just to have a lookup table on the second sheet. When the user submits a form, the script runs, looks for the ID of the last row, scans the reference table for the ID, and then fills in the details.
I think the problem I'm having is the assumption that the data from the form is already in the sheet when the script runs. The problem I noticed is that the script sometimes fails to fill in the gaps. I tried creating form submissions in a loop with the same ID and they function somewhat erratically but it seems like the last sumbission always works which would make sense if the script executions are not matching up with the form submissions. Here's the script for reference:
function fillGaps() {
// First take in the appropriate spreadsheet objects and get the sheets from it
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getSheets()[0];
var refSheet = ss.getSheets()[1];
// Here's the last rows' index
var lastRow = sheet.getLastRow();
var lastRowRef = refSheet.getLastRow();
// now this is an array of values for the last row and the student ID entered
var response = sheet.getRange(lastRow, 1, 1, 7).getValues();
var enteredID = response[0][1];
// Next we're going to try to load up the lookup table and scan for the ID
var stuIDs = refSheet.getRange(2, 4, refSheet.getLastRow()).getValues();
var row = 0;
while(enteredID != stuIDs[row] && row <= lastRowRef){
row++;
}
// Okay at this point the row variable is actually -2 from what the sheet index
// is that I'm thinking of. This is because we didn't load the first row (names)
// and the way arrays are indexed starts with 0.
row++;
row++;
// now assuming that it found a match we'll fill in the values
if(row < refSheet.getLastRow()){
// Alright now we need to wrangle that row and format the data
var matchedRow = refSheet.getRange(row, 1, 1, 6).getValues();
// modify the response
var replacement = [response[0][0],enteredID, matchedRow[0][1],matchedRow[0][0],matchedRow[0][2],matchedRow[0][4],matchedRow[0][5]];
sheet.getRange(lastRow, 1, 1, 7).setValues([replacement]) ;
}
}
So I'm wondering:
Does this seem like the right diagnosis?
If so, what would be the best way to remedy? I thought of adding a little delay into the script as well as trying to capture the submissions timestamp (not sure how to do that)
Thank you much!
The following code gives a 2D array:
var stuIDs = refSheet.getRange(2, 4, refSheet.getLastRow()).getValues();
Also,refSheet.getLastRow gives the last row, lets say it is 10 in this case. The syntax for getRange is getRange(row, column, numRows) and the last argument is the number of rows, not the last column. So in the above code the selected range would be row 2 - 11 rather than 2- 10. Unless that is what you intended, modify the code like so:
var stuIDs = refSheet.getRange(2, 4, refSheet.getLastRow()-1).getValues();
To access the values in stuIDs you should use stuIDs[row][0] (2D array) to check for matching ID. Assuming your ID was to be matched was in column 1.
Secondly, in the loop you are using the following to check for the last index in array row <= lastRowRef which will cause it go out of range(because array starts at 0 and sheet row at 1) instead use this row < stuIDs.length
Finally, in case you don't find a match you will end up with the last row and your code will end you taking the last row as the matched index. This can be prevented by using a boolean variable to check for a match.
var foundId = false
var row = 0;
var i = 0;
for (i in stuIDs){
if(stuIDs[i][0] == enteredID)
foundID = true
break
}
}
row = i + 2
if (foundID){
var matchedRow = refSheet.getRange(row, 1, 1, 6).getValues();
// modify the response
var replacement = [response[0][0],enteredID, matchedRow[0][1],matchedRow[0][0],matchedRow[0][2],matchedRow[0][4],matchedRow[0][5]];
sheet.getRange(lastRow, 1, 1, 7).setValues([replacement]) ;
}
PS: You can also use event objects to get the values of response (eventObj.values). As mentioned here: https://developers.google.com/apps-script/guides/triggers/events
Hope that helps!

Incorrect Range Height - Google Script

I'm trying to create a Google sheet script that will take a list of names and resend them to the Google Sheet. I have two columns of data, the first column contains a persons name. The second column contains multiple cells that the person in the first cell is inviting to a party. This creates a problem, the name in column 1 might be on row 2, but if they invite 20 people then column one has blank spaces rows 3-21. It may sound pointless right now to most of you, but I want to be able to sort the sheet alphabetically by the name of the person who did the inviting, AND be able to sort it into a separate sheet alphabetically by the name of the guest in Column 2, while still keeping the person who invited them tracked as well. This is the only way I could think of accomplishing the task.
I'm currently stuck on writing the array back to the sheet, I keep getting "Incorrect range height, was 1 but should be 339." I've figured out how to successfully get an array of data, filled exactly how I wanted it, but can't seem to get this part. I've searched through here and tried to implement the solutions I find, but have had no luck.
This is what I have come up with so far, and it works up until the setValues(
function inviteSorter() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var current = sheet.getSheets()[0];
var lastRow = current.getLastRow();
var rangeData = current.getRange(2,1,lastRow-1,3);
var numColumns = rangeData.getNumColumns();
// Logger.log(rangeData);
var info = rangeData.getValues();
var Name = {};
// Examines the cell in the first column, if it is empty replaces it with the name from the previous cell.
for ( var i = 0; i< info.length; i++){
if (typeof(info[i][0]) == "string" && info[i][0] == ""){
Name[i] = Name[i-1];
} else{
Name[i] = info[i][0];
}
}
var data = []
for (var i = 0; i<lastRow-1; i++){
data.push(Name[i]);
}
var writeRange = current.getRange(2,1,data.length,1);
writeRange.setValues([data]);
The value you are expecting should be a 2D array, 1 column of multiple rows. What you get when using data.push(Name[i]); is a simple array of strings.
Try this way : data.push([Name[i]]); this will return an array of arrays and should satisfy the conditions for setValues(data)
( don't forget to remove the brackets in your last setValues statement )