Related
I cannot find the way to properly simplify the nested loops to build an array of values and data validations and then set them all in the sheet in a single call to the server.
Is it even possible ??
function onEdit(){
testValidation()
}
function testValidation() {
var sheet = SpreadsheetApp.getActiveSheet();
var source = SpreadsheetApp.getActive().getRange('A3:J4').getValues()
var destination = SpreadsheetApp.getActive().getRange('M3:V4');
destination.clearDataValidations();
var validationRule = SpreadsheetApp.newDataValidation().requireCheckbox().build(); // checkbox
for(var r = 0; r <= source.length - 1; r++) {
for(var c = 0; c <= source[0].length - 1; c++) {
if(source[r][c] ==="" ){
sheet.getRange(r + 3,c + 14).clearDataValidations().setValue(null)
}else{
sheet.getRange(r + 3,c + 14).setDataValidation(validationRule).setValue("true")
}
}
}
}
Link to shared spreadsheet :
https://docs.google.com/spreadsheets/d/1fyFPIssp3zUjRmWxU9LqHvpowH8SHdMQYizNOZ3xKsA/edit?usp=sharing
In your situation, how about the following modified script?
Modified script 1:
function testValidation() {
var check = SpreadsheetApp.newDataValidation().requireCheckbox().build();
var sheet = SpreadsheetApp.getActiveSheet();
var source = sheet.getRange('A3:J4').getValues();
var values = source.map(r => r.map(c => c != "" ? check : null));
sheet.getRange('M3:V4').clearContent().setDataValidations(values).check();
}
In this modification, the checkboxes and the clear are set by setDataValidations.
I thought that this method might be low process cost.
Modified script 2:
function testValidation() {
// Ref: https://stackoverflow.com/a/21231012/7108653
const columnToLetter = column => {
let temp,
letter = "";
while (column > 0) {
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
};
var sheet = SpreadsheetApp.getActiveSheet();
var source = sheet.getRange('A3:J4').getValues();
var rangeList = source.flatMap((r, i) => r.flatMap((c, j) => c != "" ? `${columnToLetter(j + 14)}${i + 3}` : []));
sheet.getRange('M3:V4').clearDataValidations().setValue(null);
if (rangeList.length == 0) return;
sheet.getRangeList(rangeList).insertCheckboxes().check();
}
I thought that the cells of M3:V4 can be cleared using sheet.getRange('M3:V4').clearDataValidations().setValue(null).
In this modification, the checkboxes are put using insertCheckboxes() method of Class RangeList.
References:
insertCheckboxes()
setDataValidations()
We have had a sheet that gets data for a quality of work form. This has run flawlessly for over a year now, nothing at all with the sheets, form or script has ever changed since then.
But for some reason, I am now getting an error whenever we run the SendEmail function:
TypeError: Cannot read property "length" from null. (line 83, file "SendEmail")
This is where the error is now happening:
for (var i = 0; i < templateVars.length; ++i) {
The first column (Item) should have sequential numbers entered automatically whenever the script is run. Nut this now all stays blank and the email template never gets emailed.
function SendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 19);
var lastRow = dataSheet.getMaxRows();
for (var x = 0; x < dataSheet.getMaxRows() - 2; ++x) {
if(dataSheet.getRange(x+2, 3).getValue()!=""){
if(dataSheet.getRange(x+2, 15).getValue()==""){
var EMInum = dataSheet.getRange((x + 1), 1).getValue() + 1;
dataSheet.getRange(x+2, 1).setValue(EMInum);
dataSheet.getRange(x+2, 2).setFormula("=\"QoW-\"&text(A" + (x+2) + ",\"000\")");
dataSheet.getRange(x+2, 15).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,2,0)");
dataSheet.getRange(x+2, 16).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,3,0)");
dataSheet.getRange(x+2, 17).setFormula("=match(J" + (x+2) + ",CompanyName,1)");
dataSheet.getRange(x+2, 18).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,Q" + (x+2) + ",0)");
dataSheet.getRange(x+2, 19).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,Q" + (x+2) + "+1,0)");
dataSheet.getRange(x+2, 27).setFormula("=I" + (x+2)+ "&if(Z" + (x+2)+ "=\"\" ,\" OPEN\",\" CLOSED\")");
dataSheet.getRange(x+2, 28).setFormula("=if(right(AA" + (x+2) + ",4)=\"OPEN\",now()-datevalue(I" + (x+2)+ "),0)");
dataSheet.getRange(x+2, 29).setFormula("=if(AB" + (x+2) + "=0,\"e) Closed\",if(AB" + (x+2) + "<90,\"a) 0 - 90 days\",if(AB" + (x+2) + "<180,\"b) 90 - 180 days\",if(AB" + (x+2) + "<360,\"c) 180 - 360 days\",\"d) Over 360 days\"))))");
//Browser.msgBox("");
}
}
}
//
//
var templateSheet = ss.getSheets()[1];
var emailTemplate = templateSheet.getRange("A1").getValue();
var defaultCCAddress = templateSheet.getRange("B17").getValue(); // Added by zumzum as per projectid:a0CD000000xFxWQ
// Create one JavaScript object per row of data.
objects = getRowsData(dataSheet, dataRange);
// For every row object, create a personalized email from a template and send
// it to the appropriate person.
for (var i = 0; i < objects.length; ++i) {
// Get a row object
var rowData = objects[i];
// Generate a personalized email.
// Given a template string, replace markers (for instance ${"First Name"}) with
// the corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = "NO REPLY: EM&I Quality of Work Issue Submission " + dataSheet.getRange(i + 2, 2).getValue();
var emailCheck = dataSheet.getRange(i + 2, 13).getValue();
//Browser.msgBox(emailCheck);
var emailAddress = dataSheet.getRange(i + 2, 18).getValue();
var ccemailAddress = dataSheet.getRange(i + 2, 15).getValue();
if(emailCheck=="")
{
/* original code commented by zumzum as per projectid:a0CD000000xFxWQ
MailApp.sendEmail(emailAddress, emailSubject, emailText,{cc:ccemailAddress+",david.mortlock#emialliance.com,peter.gresty#emialliance.com",bcc:"richard.priddes#emialliance.com"});
dataSheet.getRange(i + 2, 13).setValue("sent - " + Date());
*/
// Start od new code added by zumzum as per projectid:a0CD000000xFxWQ
MailApp.sendEmail(emailAddress, emailSubject, emailText,{cc:ccemailAddress+","+defaultCCAddress});
dataSheet.getRange(i + 2, 13).setValue("sent - " + Date());
// End of new code added by zumzum as per projectid:a0CD000000xFxWQ
}
}
}
// Replaces markers in a template string with values define in a JavaScript data object.
// Arguments:
// - template: string containing markers, for instance ${"Column name"}
// - data: JavaScript object with values to that will replace markers. For instance
// data.columnName will replace marker ${"Column name"}
// Returns a string without markers. If no data is found to replace a marker, it is
// simply removed.
function fillInTemplateFromObject(template, data) {
var email = template;
// Search for all the variables to be replaced, for instance ${"Column name"}
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var i = 1; i < templateVars.length; i++) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}
return email;
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
//////////////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}```
The error you are getting can be reproduced by running fillInTemplateFromObject(emailTemplate, rowData) with any string for emailTemplate that does not contain a placeholder in the form ${"foo"} (the literal double quotes are required per the regex /\$\{\"[^\"]+\"\}/g).
In SendEmail, the value for emailTemplate is coming from the first sheet, cell A1. Check what value you have in that cell. Does it contain templates in the correct ${"foo"} form?
Since this error can be caused by a user manipulating the spreadsheet, consider improving fillInTemplateFromObject by checking for a successful match before trying to use the expected array.
function fillInTemplateFromObject(template, data) {
var email = template;
// Search for all the variables to be replaced, for instance ${"Column name"}
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
if (! templateVars) {
throw new Error("No templates found in your template sheet. Aborting.")
}
// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var i = 0; i < templateVars.length; i++) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}
return email;
}
You can catch that error in SendEmail and provide even more useful information:
// inside SendEmail
try {
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
} catch (error) {
throw new Error("In spreadsheet " + ss.getUrl() + " sheet " + templateSheet.getSheetName() + " row " + (i+1) + " there were no templates found.")
}
If you still need help debugging the error, use the apps script debugger or use the various logging options built into apps script to output the state of your data at run time.
Why are you using ++i rather than i++? My guess is this is the problem, if templateVars is an array, you are getting to the end of the array and trying to run it once on a row that doesn't exist. Maybe before, this was an empty row, but now the last row is the end of the sheet.
Knowing nothing else about your code I'd change:
for (var i = 0; i < templateVars.length; ++i) {
to
for (var i = 1; i < templateVars.length; i++) {
Click here for Sample Sheet
I need a solution that matches a cell value (Sheet1! Q5) to a range in another tab/sheet (NegotiationData! A1:O1) and paste the relevant data fetched from the first sheet under the designated columns of the second sheet under the matched value.
For example, if Sheet1!Q5 matches with the name in NegotiationData! A1 then do the following
Fetch Sheet1! R6 and paste in NegotiationData!A3:A
Fetch Sheet1! Q6 and paste in NegotiationData!B3:B
Fetch Sheet1! Q7 and paste in NegotiationData!C3:C
Also, each time the script runs it should not overwrite data but find the next empty row and paste the values.
I have an incomplete script that I'm trying to achieve the above from my research from various posts but since I'm just a week old to coding I'm not able to go any further than where I have got with the below script.
I'm not finding how to match the value and fetch the relevant data and paste them below the matched value.
Please help!
The Incomplete / Incorrect Script (File Name: NegotiationSubmit)
function submitNegotiation() {
var sh, id, v, estNum, negotiation, negoNotes, i;
sh = SpreadsheetApp.getActive();
id = sh.getSheetByName('Sheet1').getRange('Q5').getValue();
v = sh.getRange('R6').getValue();
estNum = Number(sh.getRange('Q6').getValue().split(" ")[1]);
negoNotes = sh.getRange('Q7').getValue();
negotiation =sh.getSheetByName('NegotiationData').getRange('A1:O');
if(v && estNum) {
negotiation.setValues(negotiation.getValues()
.map(function (r, i) {
if (r[0] == id) {
r[1] = v;
r[2] = estNum;
r[3] = negoNotes;
}
return r;
})
)
}
}
How about this modification?
Modification points :
Retrieve values of "Q5:R7" at once, and the values are converted to the import values.
Use the destructuring assignment for retrieving each value.
Import the converted values using the number of column retrieved by ids[0][i] == id.
Modified script :
function submitNegotiation() {
var id, estNum, v, negoNotes;
var sh = SpreadsheetApp.getActive();
var values = sh.getSheetByName('Sheet1').getRange("Q5:R7").getValues();
[id] = values[0];
[estNum, v] = values[1];
[negoNotes] = values[2];
// estNum = Number(estNum.split(" ")[1]); // If you want to use "estNum = Number(sh.getRange('Q6').getValue().split(" ")[1]);", please use this line.
var sh2 = sh.getSheetByName('NegotiationData');
var ids = sh2.getRange("A1:O1").getValues();
for (var i=0; i<ids[0].length; i++) {
if (ids[0][i] == id) {
sh2.getRange(sh2.getLastRow() + 1, i + 1, 1, 3).setValues([[v, estNum, negoNotes]]);
}
}
}
Note :
I was confused to the following points.
In your script, estNum is Number(sh.getRange('Q6').getValue().split(" ")[1]);. But in your sample spreadsheet, Estimate 1 of cell "Q6" is used.
I commented this in modified script.
In your sample spreadsheet, "Story ID" is 1. But in your script, it's US-001 of cell "R6".
In this modified script, US-001 of cell "R6" was used.
If I misunderstand your question, I'm sorry.
Edit :
function submitNegotiation() {
var id, estNum, v, negoNotes;
var sh = SpreadsheetApp.getActive();
var values = sh.getSheetByName('Sheet1').getRange("Q5:R7").getValues();
[id] = values[0];
[estNum, v] = values[1];
[negoNotes] = values[2];
estNum = Number(estNum.split(" ")[1]); // If you want to use "estNum = Number(sh.getRange('Q6').getValue().split(" ")[1]);", please use this line.
var sh2 = sh.getSheetByName('NegotiationData');
var ids = sh2.getRange("A1:O1").getValues();
for (var i=0; i<ids[0].length; i++) {
if (ids[0][i] == id) {
var temp = sh2.getRange(1, i + 1, sh2.getLastRow(), 3).getValues();
for (var j=temp.length-1; j>=0; j--) {
if (temp[j].join("") != "") {
sh2.getRange(j + 2, i + 1, 1, 3).setValues([[v, estNum, negoNotes]]);
break;
}
}
}
}
}
I realize that this does not resemble your code. Sorry about that. I'm learning too. But I'm putting it up anyway to provide an alternative method that includes finding the last row of the appropriate column...
function submitNegotiation() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet1');
var negotiationData = ss.getSheetByName('NegotiationData');
// Sheet1 variables
var user = sheet1.getRange('Q5').getValue();
var storyId = Number(sheet1.getRange('R6').getValue().split("-")[1]);
var estimateNum = sheet1.getRange('Q6').getValue();
var note = sheet1.getRange('Q7').getValue();
var pointers = [storyId, estimateNum, note];
// NegotiationData variables
var range = negotiationData.getDataRange().getValues();
var columns = negotiationData.getLastColumn();
var users = negotiationData.getRange(1, 1, 1, columns).getValues();
for(var i = 0; i < columns; i++) {
// match user with users to get column number
if(users[0][i] == user) {
var col = negotiationData.getRange(1, i + 1).getColumn();
// count rows in col
var rowCount = 1;
for(var i = 1; i < range.length; i++) {
if (range[i][col - 1] != "") {
rowCount++;
}
}
// assign pointers
var newRow = rowCount + 1;
for(var j = 0; j < pointers.length; j++) {
negotiationData.getRange(newRow, col, 1, 1).setValue(pointers[j]);
col++;
}
}
}
}
The spreadsheet has some cells with cell contents that are separated by commas, or a new line.
123, 876, 456
Column "C" is the column that determines whether a row should be split up into multiple rows.
EXAMPLE Spreadsheet
Information from the Form goes into the "Form Submission" page.
We have a specific format that we must meet to submit to our report tracking software that requires the issue numbers (found in Column C) to be separated into their own rows with the information found in Columns A:B, D:J remaining the same (see Desired Outcome sheet).
I found a similar question and we implemented it into our Google Sheets.
This script requires, on a separate sheet, the function =result('FormSubmission'!A2:J) to be placed in the first column / row that we wish the data to be displayed (see "Current Outcome" sheet, Cell A2.)
Here is the coding that we are using:
function result(range) {
var output2 = [];
for(var i = 0, iLen = range.length; i < iLen; i++) {
var s = range[i][2].split("\n");
for(var j = 0*/, jLen = s.length; j < jLen; j++) {
var output1 = [];
for(var k = 0, kLen = range[0].length; k < kLen; k++) {
if(k == 2) {
output1.push(s[j]);
} else {
output1.push(range[i][k]);
}
}
output2.push(output1);
}
}
return output2;
}
function results(range) {
var output2 = [];
for(var i = 0 /, iLen = range.length; i < iLen; i++) {
var s = range[i][2].split(",");
for(var j = 0 /, jLen = s.length; j < jLen; j++) {
var output1 = []/;
for(var k = 0, kLen = range[0].length; k < kLen; k++) {
if(k == 2 /) {
output1.push(s[j]);
} else {
output1.push(range[i][k]);
}
}
output2.push(output1);
}
}
return output2;
}
If someone submits multiple issue numbers separated by commas in the form, the row needs to be split up into multiple rows, as shown in the Desired Outcome sheet.
Here is some code that I tested, and it works. It also works for cells that have both new lines, and comma separated values. It does not required that the range be passed in. . . . . . Don't need that for this code. It writes the new rows directly to the 'Current Outcome' sheet.
function result() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var frmSubmissionSheet = ss.getSheetByName('Form Submission');
var desiredOutcomeSheet = ss.getSheetByName('Current Outcome');
var data = frmSubmissionSheet.getRange(1, 1, frmSubmissionSheet.getLastRow(), frmSubmissionSheet.getLastColumn()).getValues();
var issueNumbers = "",
hasComma = false,
arrayOfIssueNumbers = [],
arrayRowData = [],
thisRowData,
hasNewLine;
for (var i=0;i<data.length;i+=1) {
if (i===0) {continue}; //Skip row 1
issueNumbers = data[i][2];
hasComma = issueNumbers.indexOf(",") !== -1;
hasNewLine = issueNumbers.indexOf("\n") !== -1;
Logger.log(hasNewLine)
if (!hasComma && !hasNewLine) {
desiredOutcomeSheet.appendRow(data[i]);
continue; //Continue to next loop, there are no multiple issue numbers
};
if (hasNewLine) {
var arrayNewNewLine = issueNumbers.split("\n");//Get rid of new line
issueNumbers = arrayNewNewLine.toString(); //Back to string. Handles cells with both new line and commas
};
arrayOfIssueNumbers = [];
arrayOfIssueNumbers = issueNumbers.split(",");
for (var j=0;j<arrayOfIssueNumbers.length;j+=1) {
arrayRowData = []; //Reset
thisRowData = [];
thisRowData = data[i];
for (var k=0;k<thisRowData.length;k+=1) {
arrayRowData.push(thisRowData[k]);
};
arrayRowData.splice(2, 1, arrayOfIssueNumbers[j]);
desiredOutcomeSheet.appendRow(arrayRowData);
};
};
};
In addition to Sandy's contribution, here is some alternative code:
function extract(range, colToSplit, delimiter) {
var resArr = [], row;
range.forEach(function (r) {
r[colToSplit-1].replace(/(?:\r\n|\r|\n)(\d|\w)/g,", ").split(delimiter)
.forEach(function (s) {
row = [];
r.forEach(function (c, k) {
row.push( (k === colToSplit-1) ? s.trim() : c);
})
resArr.push(row);
})
})
return resArr;
}
This is a custom function that takes three arguments:
the range
the column on which the splitting should be based
the delimiter to split by
can be used in the spreadsheet like so:
=extract('Form Submission'!A1:J, 3, ", ")
The code subsitutes all new line characters (that are followed by a digit or a letter) to comma's and splits (based on column 3) using the comma as a delimiter.
I hope that helps ?
I have a situation where a script is taking input data and sending it to a spreadsheet. After a while, this spreadsheet becomes too big.
Right now we have to manually move the items from the the primary spreadsheet to a new one. The reason is that not everyone is familiar with the code and are willing to change the ID in the code.
I would like to know if there is a way to open the spreadsheet by name. If not, is there a better way of achieving what we need (described above)
The DocsList service used in one of the answers no longer functions as it has been depreciated. I updated my scripts to look more like the following.
// Open the file
var FileIterator = DriveApp.getFilesByName(FileNameString);
while (FileIterator.hasNext())
{
var file = FileIterator.next();
if (file.getName() == FileNameString)
{
var Sheet = SpreadsheetApp.open(file);
var fileID = file.getId();
}
}
The replacement for DocsList is DriveApp https://developers.google.com/apps-script/reference/drive/drive-app
Update: DocsList has now been sunset. Use DriveApp.getFilesByName(name) instead.
David has provided some good code for shuffling your data around. If all you really did need was just to open a spreadsheet by name then this will do the trick:
function getSpreadsheetByName(filename) {
var files = DocsList.find(filename);
for(var i in files)
{
if(files[i].getName() == filename)
{
// open - undocumented function
return SpreadsheetApp.open(files[i]);
// openById - documented but more verbose
// return SpreadsheetApp.openById(files[i].getId());
}
}
return null;
}
The way that I do something similar to what you are asking for is to first have a script make a copy of my spreadsheet (which I will call a frozen backup) that is getting too big. Once I safely have the copy, I then have the same script delete all those rows from the too big spreadsheet that are no longer required. (I believe that having multiple frozen backups does not cost the google account anything, so this is viable)
Note that I delete rows one by one; this takes time. I do this since I don't delete all the rows below a point, but only certain rows which match a condition.
In my case I do have another small procedure in addition to the above, which is to have the script copy all the rows that I am about to delete into a third spreadsheet (in addition to the frozen backup), but this seems to be more that you have asked for.
This is my code (note that the main spreadsheet, in the sheet we are going to remove rows from, named 'Original', has column A as Time Stamp for each row; the cell A1 is called Time Stamp):
function ssCopy() {
var id = "0ArVhODIsJ2.... spreadsheet key of the master spreadsheet";
var smsSS = SpreadsheetApp.openById(id);
var recordingSS = SpreadsheetApp.openById("0AvhOXv5OGF.... spreadsheet key of archive spreadsheet");// you probably wont be using this
var recordingSMSCopiesSheet = recordingSS.getSheets()[0];
var outgoingSMSsheet = smsSS.getSheetByName("Original");
outgoingSMSsheet.getRange("A1").setValue("Time Stamp");
var startRow = 2;
var numRows = outgoingSMSsheet.getDataRange().getLastRow();
var numCols = 13;
var dataRange = outgoingSMSsheet.getRange(startRow, 1, numRows, numCols);
var objects = getRowsData(outgoingSMSsheet, dataRange); // Create one JavaScript object per row of data.
var rowDataNumberArray = [];
var rowToDeleteIndex = [];
for (var i = 0; i < objects.length; ++i) { // Get a row object
var rowData = objects[i];
if( Date.parse(rowData.timeStamp) > Date.parse(ScriptProperties.getProperty('lastDate')) && (rowData.done == 1) ){ //these are not used if these same 2 lines are inserted instead of here, downbelow
var rowStuff = []
rowToDeleteIndex.push(i);
for(n in objects[i]){
rowStuff.push( objects[i][n] )}
rowDataNumberArray.push( rowStuff )};
Logger.log("rowData.number1 = " + rowStuff);
}
Logger.log(" rowDataNumberArray ~ " + rowDataNumberArray);
if(rowDataNumberArray.length > 0)
{
for(row in rowDataNumberArray)
{recordingSMSCopiesSheet.appendRow(rowDataNumberArray[row]);}
}
spreadsheetFrozenBackup(id)
for( var i = rowToDeleteIndex.length-1; i >= 0; i-- ) //backwards on purpose
outgoingSMSsheet.deleteRow(rowToDeleteIndex[i]+ 0 + startRow); //so we don't have to re-calculate our row indexes (thanks to H. Abreu)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function spreadsheetFrozenBackup(id) {
// Get current spreadsheet.
var ss = SpreadsheetApp.openById(id);
// Name the backup spreadsheet with date.
var bssName = " Frozen Spreadsheet at: " + Utilities.formatDate(new Date(), "GMT+1:00", "yyyy-MM-dd'T'HH:mm:ss") + " : " + ss.getName() ;
var bs = SpreadsheetApp.openById((DocsList.copy(DocsList.getFileById(ss.getId()), bssName)).getId());
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
//////////////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// setRowsData fills in one row of data per object defined in the objects Array. // https://developers.google.com/apps-script/storing_data_spreadsheets
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}