I'm trying to use a for loop to change values and to add notes to the ones that I change. since I'm doing it through arrays and not each row individually, my question is, is it possible to get where there isnt a note on the cell to be nothing in the array?
It's through the google scripts system, I've tried looking everywhere but can't find anything on the subject, hoping there's a wizard here.
edit: snippet of script
function CheckHours() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Copy of PNC Roster');
var lastrow = sheet.getLastRow();
var response;
var hoursList = [];
var notesList = [];
var bmidRange = sheet.getRange("L:L").getValues();
var notesRange = sheet.getRange("J:J").getNotes();
for (var i = 0; i < lastrow; i++) {
if (bmidRange[i] > 1) {
//response = UrlFetchApp.fetch('InsertWebsite/?bm=' + bmidRange[i] + '&fr=7');
var seconds = 59378;
var hours = seconds/60/60;
hoursList.push([hours]);
var note = "Activity Check performed: "+ new Date() + "\n\n" + notesRange[i];
notesList.push([note]);
Logger.log(hours);
} else if(bmidRange[i] == "") {
notesList.push('INSERT BATTLEMETRICS ID');
} else {
hoursList.push(bmidRange[i]);
notesList.push(notesRange[i]);
}
}
sheet.getRange("J:J").offset(0, 0, hoursList.length).setNotes(notesList);
sheet.getRange("J:J").offset(0, 0, hoursList.length).setValues(hoursList);
}
What I'm trying to do when I'm pushing the cell values is that they get an appropriate note along with them, but because the variable notesRange is not the same amount as getValues gets, then where there is no notes, instead having a null value in the array basically, is this possible??
Related
I am trying to pull the value from the cell above when a cell is blank, however, every-time I run my code it removes the formula from the cell above and makes it text. Can someone help me figure out how to keep the formula intact? Here is the code I utilized that worked with pulling a value down:
function fill_2(){
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1UvBuVp9N866J-3677dXsPYYpZZRd7i1O4GIlPkBJWbA/edit#gid=713176516');
var sheet = ss.getSheetByName("All Client Log-ins");
var tracts = ss.getRange("All Client Log-ins!F2:F").getValues();
var allTractList = [];
var title;
var len = tracts.length;
for (var row = 0; row < len; row++) {
if (tracts[row] !='') {
title = tracts[row];
allTractList.push([title]);
Logger.log(title);
} else allTractList.push([title]);
}
Logger.log('allTractList' + allTractList);
sheet.getRange("F2").offset(0,0,allTractList.length).setValues(allTractList);
return allTractList;
}
Here's what I think your code boils down to:
function fill_2(){
const ss = SpreadsheetApp.openById('1UvBuVp9N866J-3677dXsPYYpZZRd7i1O4GIlPkBJWbA');
var sh1 = ss.getSheetByName("All Client Log-ins");
Logger.log(sh1.getRange("F2:F" + sh1.getLastRow()).getValues().flat().filter(e => e));
return sh1.getRange("F2:F" + sh1.getLastRow()).getDisplayValues().flat().filter(e => e);
}
I have searched many possible answers but cannot seem to find one that works. I have a Google Sheet with about 1600 rows that I need to split into about 70 different tabs (with about 20-30 rows in each one) based on the value in the column titled “room”. I have been sorting and then cutting and pasting but for 70+ tabs this is very tedious.
I can use the Query function but I still need to create a new tab, paste the function and update the parameter for that particular tab.
This script seemed pretty close:
ss = SpreadsheetApp.getActiveSpreadsheet();
itemName = 0;
itemDescription = 1;
image = 2;
purchasedBy = 3;
cost = 4;
room = 5;
isSharing = 6;
masterSheetName = "Master";
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Update Purchases')
.addItem('Add All Rows To Sheets', 'addAllRowsToSheets')
.addItem('Add Current Row To Sheet', 'addRowToNewSheet')
.addToUi();
}
function addRowToNewSheet() {
var s = ss.getActiveSheet();
var cell = s.getActiveCell();
var rowId = cell.getRow();
var range = s.getRange(rowId, 1, 1, s.getLastColumn());
var values = range.getValues()[0];
var roomName = values[room];
appendDataToSheet(s, rowId, values, roomName);
}
function addAllRowsToSheets(){
var s = ss.getActiveSheet();
var dataValues = s.getRange(2, 1, s.getLastRow()-1, s.getLastColumn()).getValues();
for(var i = 0; i < dataValues.length; i++){
var values = dataValues[i];
var rowId = 2 + i;
var roomName = values[room];
try{
appendDataToSheet(s, rowId, values, roomName);
}catch(err){};
}
}
function appendDataToSheet(s, rowId, data, roomName){
if(s.getName() != masterSheetName){
throw new Error("Can only add rows from 'Master' sheet - make sure sheet name is 'Master'");
}
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
var roomSheet;
if(sheetNames.indexOf(roomName) > -1){
roomSheet = ss.getSheetByName(roomName);
var rowIdValues = roomSheet.getRange(2, 1, roomSheet.getLastRow()-1, 1).getValues();
for(var i = 0; i < rowIdValues.length; i++){
if(rowIdValues[i] == rowId){
throw new Error( data[itemName] + " from row " + rowId + " already exists in sheet " + roomName + ".");
return;
}
}
}else{
roomSheet = ss.insertSheet(roomName);
var numCols = s.getLastColumn();
roomSheet.getRange(1, 1).setValue("Row Id");
s.getRange(1, 1, 1, numCols).copyValuesToRange(roomSheet, 2, numCols+1, 1, 1);
}
var rowIdArray = [rowId];
var updatedArray = rowIdArray.concat(data);
roomSheet.appendRow(updatedArray);
}
But I always get an unexpected token error on line 51 or 52:
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
(And obviously the column names, etc. are not necessarily correct for my data, I tried changing them to match what I needed. Not sure if that was part of the issue.)
Here is a sample of my data: https://docs.google.com/spreadsheets/d/1kpD88_wEA5YFh5DMMkubsTnFHeNxRQL-njd9Mv-C_lc/edit?usp=sharing
This should return two separate tabs/sheets based on room .
I am obviously not a programmer and do not know Visual Basic or Java or anything. I just know how to google and copy things....amazingly I often get it to work.
Let me know what else you need if you can help.
Try the below code:
'splitSheetIntoTabs' will split your master sheet in to separate sheets of 30 rows each. It will copy only the content not the background colors etc.
'deleteTabsOtherThanMaster' will revert the change done by 'splitSheetIntoTabs'. This function will help to revert the changes done by splitSheetIntoTabs.
function splitSheetIntoTabs() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var header = rows[0];
var contents = rows.slice(1);
var totalRowsPerSheet = 30; // This value will change no of rows per sheet
//below we are chunking the toltal row we have into 30 rows each
var contentRowsPerSheet = contents.map( function(e,i){
return i%totalRowsPerSheet===0 ? contents.slice(i,i+totalRowsPerSheet) : null;
}).filter(function(e){ return e; });
contentRowsPerSheet.forEach(function(e){
//crate new sheet here
var currSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
//append the header
currSheet.appendRow(header);
//populate the rows
e.forEach(function(val){
currSheet.appendRow(val);
});
});
}
// use this function revert the sheets create by splitSheetIntoTabs()
function deleteTabsOtherThanMaster() {
var sheetNotToDelete ='Master';
var ss = SpreadsheetApp.getActive();
ss.getSheets().forEach(function(sheet){
if(sheet.getSheetName()!== sheetNotToDelete)
{
ss.deleteSheet(sheet);
}
});
}
I was using Kessy's nice script, but started having trouble when the data became very large, where the script timed out. I started looking for ways to reduce the amount of times the script read/wrote to the spreadsheet (rather than read/write one row at a time) and found this post https://stackoverflow.com/a/42633934
Using this principle and changing the loop in the script to have a loop within the loop helped reduce these calls. This means you can also avoid the second call to append rows (the "else"). My script is a little different to the examples, but basically ends something like:
`for (var i = 1; i < theEmails.length; i++) {
//Ignore blank Emails and sheets created
if (theEmails[i][0] !== "" && !completedSheets.includes(theEmails[i][0])) {
//Set the Sheet name = email address. Index the sheets so they appear last.
var currentSheet = theWorkbook.insertSheet(theEmails[i][0],4+i);
//append the header
//To avoid pasting formulas, we have to paste contents
headerFormat.copyTo(currentSheet.getRange(1,1),{contentsOnly:true});
//Now here find all the rows containing the same email address and append them
var theNewRows =[];
var b=0;
for(var j = 1; j < rows.length; j++)
{
if(rows[j][0] == theEmails[i][0]) {
theNewRows[b]=[];//Initial new array
theNewRows[b].push(rows[j][0],rows[j][1],rows[j][2],rows[j][3],rows[j][4],rows[j][5],rows[j][6],rows[j][7]);
b++;
}
}var outrng = currentSheet.getRange(2,1,theNewRows.length,8); //Make the output range the same size as the output array
outrng.setValues(theNewRows);
I found a table of ~1000 rows timed out, but with the new script took 6.5 secs. It might not be very neat, as I only dabble in script, but perhaps it helps.
I have done this script that successfully gets each room and creates a new sheet with the corresponding room name and adding all the rows with the same room.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
// This var will contain all the values from column C -> Room
var columnRoom = sheet.getRange("C:C").getValues();
// This var will contain all the rows
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
//Set the first row as the header
var header = rows[0];
//Store the rooms already created
var completedRooms = []
//The last created room
var last = columnRoom[1][0]
for (var i = 1; i < columnRoom.length; i++) {
//Check if the room is already done, if not go in and create the sheet
if(!completedRooms.includes(columnRoom[i][0])) {
//Set the Sheet name = room (except if there is no name, then = No Room)
if (columnRoom[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
}
//append the header
currentSheet.appendRow(header);
currentSheet.appendRow(rows[i]);
completedRooms.push(columnRoom[i][0])
last = columnRoom[i][0]
} else if (last == columnRoom[i][0]) {
// If the room's sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
currentSheet.appendRow(rows[i]);
}
}
}
Please test it and don't hesitate to comment for improvements.
My spreadsheet is composed of a main sheet that is populated using a form plus several other sheets for the people who work with the responses submitted through the form. A script delegates the form responses to these other sheets depending on the type of item described in the response.
The problem is, when Person A deletes an item from their respective sheet, it doesn't delete in the main sheet.
My idea is that when you type a set password into the corresponding cell in row 'Q' in Person A's sheet, it matches the item by timestamp to the original form submission and deletes both the version of the item in Person A's sheet as well as the main sheet. However, I can't figure out what to set the range to to get it to point to the row in the array. Everything I have tried has sent back "undefined" in the debugger and won't delete anything. I think the problem is that I don't know how to get the row from the array that I have made. See my code below:
function onEdit() {//copies edited items from individual selector sheets back onto main spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var actSheet = ss.getActiveSheet();
var responseSheet = ss.getSheetByName("Item Request");
var actCell = actSheet.getActiveCell();
var actRow = actCell.getRow();
var actVal = actCell.getValue();
var actLoc = actCell.getA1Notation();
var last = actSheet.getLastRow();
var respLast = responseSheet.getLastRow();
var dataA = responseSheet.getRange(1, 1, respLast, 1).getValues(); //compiles an array of data found in column A through last row in response sheet
var tstamp1 = actSheet.getRange(actCell.getRow(), 1);
var tsVal1 = tstamp1.getValue();
var colEdit = actCell.getColumn();
//===========THIS IS WHERE I'M STUCK=======================
if ((actVal == "p#ssword") && (colEdit == 17)) {
for (i = 1; i < dataA.length; i++) {
if (dataA[i][0].toString == tsVal1.toString()) {
responseSheet.deleteRow(i + 1);
actSheet.deleteRow(actRow);
break;
}
}
}
else if (colEdit == 15) { //checks the array to see if the edit was made to the "O" column
for (i = 1; i < dataA.length; i++) {//checking for timestamp match and copies entry
if (dataA[i][0].toString() == tsVal1.toString()) {
var toEdit = responseSheet.getRange(i + 1, 16);
toEdit.setValue(actVal);
}
}
}
else if (colEdit == 16) { // checks the array to see if the edit was made in the "P" column
for (i = 1; i < dataA.length; i++) {//checking for timestamp match and copies entry
if (dataA[i][0].toString() == tsVal1.toString()) {
var toEdit = responseSheet.getRange(i + 1, 17);
toEdit.setValue(actVal);
}
}
}
else {return;}
}//end onEdit
I don't believe these are proper commands delRow.deleteRow();actCell.deleteRow(); Take a look at the documentation;
Okay I rewrote that function for you a bit but I'm stilling wondering about a couple of lines.
function onEdit(e)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var actSheet = ss.getActiveSheet();
var responseSheet = ss.getSheetByName("Item Request");
var actCell = actSheet.getActiveCell();
var actRow = actCell.getRow();
var actVal = actCell.getValue();
var colEdit = actCell.getColumn();
var respLast = responseSheet.getLastRow();
var dataA = responseSheet.getRange(1, 1, respLast, 1).getValues();
var tstamp1 = actSheet.getRange(actRow, 1);
var tsVal1 = tstamp1.getValue();
for(var i=0;i<dataA.length;i++)
{
if(new Date(dataA[i][0]).valueOf()==new Date(tsVal1).valueOf())
{
if (actVal=="p#ssword" && colEdit==17)
{
responseSheet.deleteRow(i + 1);
actSheet.deleteRow(actRow);
}
else if(colEdit==15)
{
var toEdit = responseSheet.getRange(i + 1, 16);//?
toEdit.setValue(actVal);//?
}
else if (colEdit == 16)
{
var toEdit = responseSheet.getRange(i + 1, 17);//?
toEdit.setValue(actVal);//?
}
}
}
}
Can you explain the function of the lines with question marked comments?
I have created a google spreadsheet to automatically convert into a google form, so i don't have to manually enter all the questions into the google form.
I am writing google app script and managed to get all the questions.I am trying to divide the form in to sections depending on the first column of the sheet. So if the first column is "1" questions corresponding to it should be on the first section and if it is "2" it should create another section.And so on.
How can i do that? what will be the code? I have attached the google sheet as here Google spreadsheet
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var range = ss.getDataRange();
var data = range.getValues();
var numberRows = range.getNumRows();
var numberColumns = range.getNumColumns();
var firstRow = 1;
var form = FormApp.openById('1hIQCLT_JGLcvjz44vXTvP5ziia6NnwCqWBxYT4h2uCk');
var items = form.getItems();
var ilength = items.length;
for (var i=0; i<items.length; i++)
{
form.deleteItem(0);
}
for(var i=0;i<numberRows;i++)
{
Logger.log(data);
var questionType = data[i][0];
if (questionType=='')
{
continue;
}
//choose the type of question from the first column of the spreadsheet
else if(questionType=='1')
{
var rowLength = data[i].length;
var currentRow = firstRow+i;
var currentRangeValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(currentRow,1,1,rowLength).getValues();
var getSheetRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getDataRange();
var numberOfColumnsSheet = getSheetRange.getNumColumns();
var numberOfOptionsInCurrentRow = numberOfColumnsSheet;
var lastColumnInRange = String.fromCharCode(64 + (numberOfOptionsInCurrentRow));
var range_string = 'C' + currentRow + ":" + lastColumnInRange + currentRow;
var optionsArray = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(range_string).getValues();
var choicesForQuestion =[];
for (var j=0;j<optionsArray[0].length;j++)
{
choicesForQuestion.push(optionsArray[0][j]);
}
form.addMultipleChoiceItem().setTitle(data[i][1]).setHelpText("").setChoiceValues(choicesForQuestion).setRequired(true);
}
else
{
continue;
}
}
form.addParagraphTextItem()
.setTitle('Please specify and attach relevant documents'); // add the text question at the last
form.addPageBreakItem().setTitle('Identity - Asset Management').setHelpText("")();
}
googleSheet
If you want to use the same exact format for the next section you can get away with a simple counter. I have written a successful script variant, but it depends on what you really want.
Some of the changes I would do
for (i = 0; i < items.length; i++) {
form.deleteItem(items[i])
}
instead of the current form.deleteItem(0);. Otherwise I see that you grab all the data, however you do not utilize it. Calling the spreadsheet app each time you want the options causes it to run a lot slower. More on that for loop: move the Logger.log(data); outside of the loop. There is no reason for you to keep logging the full data range each time you go to the next row of the data. Or change it to Logger.log(data[i]); which would make more sense.
You already do a
if (questionType=='') {
continue;
}
to skip over the empty lines, so not really sure what that last else is meant for. The loop will fall through to the next option on its own anyway.
Now the way your set up would work is that your questions in the spreadsheet must be in order. That is you cannot have
Section 1
Section 2
Section 1
as that will create 3 sections instead of 2. However let's move along with the assumption that the spreadsheet would only be set up in a way where you will only have a sequence like
Section 1
Section 1
Section 2
In that case you should utilize your data and questionType by adding a counter var sectionCount = 0 somewhere before the loop. Then inside of your for loop you do a simple
else if (questionType != sectionCount) {
form.addSectionHeaderItem().setTitle('Section ' + questionType)
sectionCount++
}
this will create the section (provided that the numbers are always increasing by 1 in Column A). Then in the same for loop you do not need any more if statements and can just use
items = data[i].slice(2, data[i].length + 1)
items = items.filter(chkEmpty)
form.addMultipleChoiceItem().setTitle(data[i][1]).setChoiceValues(items)
where
function chkEmpty(val){
return val != ''
}
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
var range = ss.getDataRange();
var data = range.getValues();
var numberRows = range.getNumRows();
var numberColumns = range.getNumColumns();
var firstRow = 1;
var form = FormApp.openById('1xlXDZB5jhbUWpWHxxJwY-ut5oYkh4OfIQSTGsnwGTW4');
var sectionCount = 0
// deletes the previous changes
var items = form.getItems();
var ilength = items.length;
for (i = 0; i < items.length; i++)
{
form.deleteItem(items[i])
}
for(var i=0;i<numberRows;i++)
{
var questionType = data[i][0];
if (questionType=='')
{
continue;
}
else if (questionType != sectionCount )
{
if (sectionCount != 0 )
{
// form.addParagraphTextItem()
// .setTitle('Please specify and attach relevant documents'); // add the text question at the last
// write the description here using SectionCount
}
sectionCount++ // add new section to the form
form.addSectionHeaderItem().setTitle('Section ' + questionType).setHelpText(""); // add section header and title
}
items = data[i].slice(2, data[i].length + 1)
items = items.filter(chkEmpty)
form.addMultipleChoiceItem().setTitle(data[i]
[1]).setChoiceValues(items).setRequired(true);
if ( i == (numberRows-1)){
// form.addParagraphTextItem()
// .setTitle('Please specify and attach relevant documents');
}
}
function chkEmpty(val)
{
return val != ''
}
Logger.log(data);
}
Column C has an ID in it that pertains to several rows, but only the first row has an ID in it.
I need to copy that ID value to the blank cells beneath, until I hit a cell that has another value in it.
I have tried adapting this script but it hits a timeout error.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var last = sheet.getLastRow();//how many times should I do this?
for (i = 5528; i < last; i++) {
var test = sheet.getRange(i, 1,1,1);
//Logger.log(test);
//looks to see if the cell is empty
if (test.isBlank()) {
var rewind = sheet.getRange(i-1, 1, 1, 1).getValues();//gets values from the row above
sheet.getRange(i, 1, 1, 1).setValues(rewind);//sets the current range to the row above
}
}
}
i is set to a big number because every time it times out I have to start over!
I have read that it would be better to bring in the column in an array, work on it, then put it back out to save a lot of time.
I have tried to adapt this but can't get past the variable.
Am I on the right track? I would like to pretty up a solution for the future where I can pass a column or range and do the same thing.
Here is my failing attempt:
function FillDown2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet2");
var tracts = sheet.getRange("C15:C").getValues();
var allTractList = [];
var title;
for (var row = 0, var len = tracts.length; row < len; row++) {
if (tracts[row][0] != '') {
//response = UrlFetchApp.fetch(tracts[row]);
//doc = Xml.parse(response.getContentText(),true);
title = tracts[row][0];
//newValues.push([title]);
allTractList.push([title]);
Logger.log(title);
} else allTractList.push([title]);
}
//Logger.log('newValues ' + newValues);
Logger.log('allTractList ' + allTractList);
// SET NEW COLUMN VALUES ALL AT ONCE!
sheet.getRange("B15").offset(0, 0, allTractList.length).setValues(allTractList);
return allTractList;
}
Holy Smokes! I did it!
Not sure about why error happened but I had made some changes and got it to work!
Hope this is helpful to others:
function FillDown2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet2");
var tracts = sheet.getRange("C15:C").getValues();
var allTractList = [];
var title;
var len = tracts.length;
for (var row = 0; row < len; row++) {
if (tracts[row] != '') {
//response = UrlFetchApp.fetch(tracts[row]);
//doc = Xml.parse(response.getContentText(),true);
title = tracts[row];
//newValues.push([title]);
allTractList.push([title]);
Logger.log(title);
} else allTractList.push([title]);
}
//Logger.log('newValues ' + newValues);
Logger.log('allTractList ' + allTractList);
// SET NEW COLUMN VALUES ALL AT ONCE!
sheet.getRange("B15").offset(0, 0, allTractList.length).setValues(allTractList);
return allTractList;
}
Credit to Bryan here: