Create an array of values that were looped through - google-apps-script

I have a spreadsheet where each row in "MASTER" sheet is a task. It has checkboxes to check if it's done.
On another sheet, "Sin despachar", the data is filtered so that only the tasks which are not done show. There I have empty checkboxes to check when an incomplete task is completed.
I wrote a script so that when a button is pressed, it loops through the whole column in "Sin despachar" to see if checkboxes are checked, and for those that are, it changes the value in a master sheet.
I would like to have a confirmation pop up that mentions all the tasks it'll edit, but for that I need to somehow retrieve that list when the script runs, and I don't know how.
So what I need is to create an array or something else that contains the names of the tasks with the checkbox checked.
Does anyone know how to do this?
The task names are in column 4, and the checkboxes are in column 18.
Thanks in advance!!
function marcarEtiquetado() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
Logger.log(usuariosRange)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange( targetRow, 16);
var targetTS = targetSheet.getRange( targetRow, 17);
checkboxRange.setValue(false)
targetRange.setValue(true);
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
} ;
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}

You use alerts to confirm for every checked box individually either and action shall be carried out.
Sample:
function marcarEtiquetado() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
var ui = SpreadsheetApp.getUi();
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange(targetRow, 16);
var targetTS = targetSheet.getRange(targetRow, 17);
var response = ui.alert('Do you want to set the timestamp for row ' + (i+1) + '?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response == ui.Button.YES) {
checkboxRange.setValue(false)
targetRange.setValue(true);
SpreadsheetApp.getActiveSpreadsheet().toast("Timestamp will be set for row " + (i+1));
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Timestamp will not be set for row " + (i+1));
}
} ;
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}
If this is not what you wanted and you prefer to have a single confirmation dialog for all checked boxes, you can implement a help array and string as following:
function marcarEtiquetado2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Sin despachar");
var sheetRange = s.getDataRange();
var sheetValues = sheetRange.getValues();
var ui = SpreadsheetApp.getUi();
var rowKeeper = [];
var rowArray = ['\n'];
for (var i=sheetRange.getLastRow()-1; i>1; i--) {
// si valor en columna R (etiquetado) = TRUE
if ( sheetValues[i][17] === true) {
rowKeeper.push(i);
rowArray.push(i+1);
}
}
for (k = 0; k < rowArray.length-4; k += 5) {
rowArray[k+4] = rowArray[k+4] + "\n";
}
var rowString = rowArray.join(" ");
Logger.log(rowString);
var response = ui.alert('Do you want to set the timestamp for rows ' + rowString + '?', ui.ButtonSet.YES_NO);
// Process the user's response.
if (response == ui.Button.YES) {
for (var j = 0; j < rowKeeper.length; j++){
var i = rowKeeper[j];
var checkboxRange = s.getRange(i, 18);
var usuariosRange = s.getRange(i, 3)
var targetSheet = ss.getSheetByName("*MASTER*");
var targetRow = sheetValues[i][1];
var targetRange = targetSheet.getRange(targetRow, 16);
var targetTS = targetSheet.getRange(targetRow, 17);
checkboxRange.setValue(false)
targetRange.setValue(true);
targetTS.setValue(new Date()).setNumberFormat("dd-mm-yy hh:mm")
}
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("No action will be carried out");
}
s.getRange(3, 18, s.getLastRow()-2).setValue(false)
}

Related

Google Apps Script Substring

In my spreadsheet I have a file path to an image stored in a sub folder. The image is stored like this because I am making an app for my employer using appsheet.com. They want this app developed using AppSheet, which does not allow images to be stored directly into the spreadsheets that are used to build these app.
The data stored in the spreadsheet must also be extracted and applied to a template and I am making a Google Apps Script to do this. I have a functional script which finds the template and extract the users chosen data row, but I cannot extract the image needed.
I have been trying to make a substring of the file path to get the file name, but I have been unable to do this.
In the block of code where I am trying to create the substring, I am getting an error on the line sig = signature.getText();. The error is TypeError: signature.getText is not a function (line 176, file "Code").
This is what the file path looks like Signatures/FT101.Signed (%SIGNED%).103735.png, and the substring I need would look like this FT101.Signed (%SIGNED%).103735.png
I have tried multiple methods that were provided by other questions asked on stack overflow as well as any potential methods available in the Google Apps Script reference.
The following function takes the users input from a prompt and uses it to find the desired row number. It then takes the data from that row and applies it to a template based on the category the data falls under.
var response = {};
var sign = "";
function chooseRowMethod(templateId){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var data = sheet.getRange(2, 2, 11, 18).getValues();//starting with row 2 and column 1 as our upper-left most column, get values from cells from 1 row down, and 15 columns along - hence (2,1,1,15)
var docTitle = sheet.getRange(2, 2, 11, 1).getValues();//this is grabbing the data in field B2
var docTitleTagNumber = sheet.getRange(2, 3, 11, 1).getValues();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
for(var i = 0; i < values.length; i++){
for(var j = 0; j < values[i].length; j++){
if(values[i][j] == response){
Logger.log(i);
var row = data[i - 1];
var docId = DriveApp.getFileById(templateId).makeCopy().getId();
var doc = DocumentApp.openById(docId);
var body = doc.getActiveSection();
body.replaceText("%SITEID%", row[0]);
body.replaceText("%TAG%", row[1]);
...
body.replaceText("%SAT%", row[14]);
var signature = sheet.getRange(2, 18, 11, 1).getValues();
var sig;
var sign = {};
for(var i = 0; i < values.length; i++){
for(var j = 0; j < values[i].length; j++){
if(values[i][j] == response){
sig = signature.getText();
sign[i][0] = sig.substring(sig.indexOf("/") + 1);
}
}
}
var sigFolder = DriveApp.getFolderById("1LiJKGjTbpvRZ5RrMTQoyTuAjrozA14FN");
var file = sigFolder.getFilesByName(sign);
var image = file.getId();
body.appendImage(image);
doc.saveAndClose();
var file = DriveApp.getFileById(doc.getId());
var newFolder = DriveApp.getFolderById("16wRGBVdV0OZ5YfKhqEQSFMsux-ekGCCa");
newFolder.addFile(file);
var newDocTitle = docTitle[i - 1][0];
var newDocTagNumber = docTitleTagNumber[i - 1][0];
doc.setName(newDocTitle + " " + newDocTagNumber + " " + today);
}
}
}
}
This is where I have been attempting to get the image.
var signature = sheet.getRange(2, 18, 11, 1).getValues();
var sig;
var sign = {};
for(var i = 0; i < values.length; i++){
for(var j = 0; j < values[i].length; j++){
if(values[i][j] == response){
sig = signature.getText();
sign[i][0] = sig.substring(sig.indexOf("/") + 1);
}
}
}
var sigFolder = DriveApp.getFolderById("1LiJKGjTbpvRZ5RrMTQoyTuAjrozA14FN");
var file = sigFolder.getFilesByName(sign);
var image = file.getId();
body.appendImage(image);
This next function gives the user the prompt and applies the correct template.
function chooseRow(){
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.prompt('Please enter the Tag number of the row you wish to print.', ui.ButtonSet.OK_CANCEL);
var button = result.getSelectedButton();
response = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK".
ui.alert('Your tag number is' + response + '.');
} else if (button == ui.Button.CANCEL) {
// User clicked X in the title bar.
ui.alert('You closed the dialog.');
return 'the end';
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var category = sheet.getRange(2, 4, 11, 1).getValues();
var templateId = {};
for(var i = 0; i < values.length; i++){
for(var j = 0; j < values[i].length; j++){
if(values[i][j] == response && category[i - 1][0] == "Instrument"){
templateId = "1cx2-6ju-o7DaRPnbuYxxdvVVFeGQzpTXaXV3wMuRpqo";
chooseRowMethod(templateId);
return "";
} else if(values[i][j] == response && category[i][0] == "Motor" || values[i][j] == response && category[i][0] == "Valve"){
templateId = "1sYx_JcoDHY-pzjEDlxMMa3dtdzOOE8CyyLGQk8WHg7s";
chooseRowMethod(templateId);
return "";
}
}
}
}
The expected result is a substring of the file path that can be used to retrieve an image that can be appended to the body of a document.
Here is a link to the spreadsheet.
I did several changes to your code, including the edit proposed by Cooper. It's retrieving the substring and adding the image to the file successfully. I hope it works for you:
function chooseRow(){
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.prompt('Please enter the Tag number of the row you wish to print.', ui.ButtonSet.OK_CANCEL);
var button = result.getSelectedButton();
response = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK".
ui.alert('Your tag number is' + response + '.');
} else if (button == ui.Button.CANCEL) {
// User clicked X in the title bar.
ui.alert('You closed the dialog.');
return 'the end';
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var tags = sheet.getRange(2, 4, 11, 1).getValues();
var category = sheet.getRange(2, 3, 11, 1).getValues();
for(var i = 0; i < tags.length; i++){
if(tags[i][0] == response && category[i][0] == "Instrument"){
var templateId = "my_template_id";
chooseRowMethod(templateId, i);
return ""; // You don't need to return empty string, just return null
} else if(tags[i][0] == response && category[i][0] == "Motor" || tags[i][0] == response && category[i][0] == "Valve"){
var templateId = "my_template_id_bis";
chooseRowMethod(templateId, i);
return ""; // You don't need to return empty string, just return null
}
}
}
The function chooseRowMethod gets the row index chosen by the user in chooseRow so that it doesn't have to be looked for again:
function chooseRowMethod(templateId, rowNumber){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getRange(2, 2, 11, 18).getValues();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
var row = data[rowNumber];
var docTitle = row[1];
var docTitleTagNumber = row[2];
var docId = DriveApp.getFileById(templateId).makeCopy().getId();
var doc = DocumentApp.openById(docId);
var body = doc.getActiveSection();
body.replaceText("%SITEID%", row[0]);
body.replaceText("%TAG%", row[1]);
// ...
body.replaceText("%SAT%", row[14]);
var signature = row[17];
var sign = signature.substring(signature.indexOf("/") + 1);
var sigFolder = DriveApp.getFolderById("my_sigfolder_id");
var files=sigFolder.getFilesByName(sign);
var n = 0;
while(files.hasNext()) {
var file=files.next();
n++;
} if(n>1) {
SpreadsheetApp.getUi().alert('There is more than one file with this name: ' + sign);
}
body.appendImage(file);
doc.saveAndClose();
var file = DriveApp.getFileById(doc.getId());
var newFolder = DriveApp.getFolderById("my_newfolder_id");
newFolder.addFile(file);
doc.setName(docTitle + " " + docTitleTagNumber + " " + today);
}

Capture values and send email trigger

I managed to collect data of user typing in and by using onChange trigger, I did meet my requirements for my task. However, I realized that for example I am filling up Column A1:A4. If my A1:A3 is out of range, it will trigger the email. But if my A4 is within range, the values of A1:A3 will still trigger the email eventhough it has trigger it before. How do I make sure that the values that have been capture do not trigger the email again?
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
currentsheet = ss.getSheetName();
//var values = ss.getRange(a1Notation)
//console.log(values);
var lastcol = ss.getLastColumn();
var vibrationtemplate = HtmlService.createTemplateFromFile("vibration");
var temperaturetemplate = HtmlService.createTemplateFromFile("temperature");
//console.log(lastcol);
if((currentsheet == 'A Vibration') || (currentsheet == 'B Vibration')){
console.log(currentsheet);
for(var i =2; i<=lastcol; i++){
var cell = ss.getRange(i,lastcol).getValues();
console.log(""+cell);
if(cell > 8){
console.log("Value is more than 8 and current value is "+cell);
vibrationtemplate.vibrate = cell;
MailApp.sendEmail("someone#gmail.com",
"Parameter Out of Range Notification",
"",{htmlBody: vibrationtemplate.evaluate().getContent()});
}
}
}
if((currentsheet == 'A Temperature') || (currentsheet == 'B Temperature')){
console.log(currentsheet);
for(var i =2; i<=lastcol; i++){
var cell = ss.getRange(i,lastcol).getValues();
console.log(""+cell);
if(cell > 80){
console.log("Value is more than 80 and current value is "+cell);
temperaturetemplate.temp = cell;
MailApp.sendEmail("someone#gmail.com",
"Parameter Out of Range Notification",
"",{htmlBody: temperaturetemplate.evaluate().getContent()});
}
}
}
}
EDIT: Latest code - Using a daily trigger and only checks at the end of the day.
function myFunction() {
const ss = SpreadsheetApp.getActiveSheet();
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sheetNumber = sheets.length; //Get number of sheets within Spreadsheet
var currentSheet = ss.getIndex()-1; //Get index of current sheet with 0 indexing
var vibrationtemplate = HtmlService.createTemplateFromFile("vibration"); //Create HTML for email by grabbing template from vibration.html
var temperaturetemplate = HtmlService.createTemplateFromFile("temperature"); //Create HTML for email by grabbing template from temperature.html
const vibrationlimit = 8; //Set vibrationlimit as constant equals to 8
const temperaturelimit = 80; //Set temperaturelimit as constant equals to 80
var currentDate = new Date(); //Get system Date and Time
var currentDay = currentDate.getDate(); //Extract Date from Full Date(currentDate)
var currentMonth = currentDate.getMonth() +1; //Extract Month from Full Date(currentDate), add +1 as month index start from 0.
for (var z = currentSheet ; z<sheetNumber ; ++z ){
SpreadsheetApp.setActiveSheet(sheets[z])
var lastcol = sheets[z].getLastColumn();
var lastrow= sheets[z].getLastRow();
var cellDate = sheets[z].getRange(1,lastcol).getValues();
var formattedCellDate = new Date(cellDate);
var cellDay = formattedCellDate.getDate();
var cellMonth = formattedCellDate.getMonth() + 1;
if((z==0) || (z==2)){
if((cellDay == currentDay) && (cellMonth == currentMonth)){
for(var i = 2; i<=lastrow; i++){
var scxvibrationname = sheets[z].getRange(i,1).getValues();
var vibration = sheets[z].getRange(i,lastcol).getValues();
if(vibration > vibrationlimit){
Logger.log("Vibration over 8 - Current Value is "+vibration);
vibrationtemplate.vibrate = vibration;
vibrationtemplate.scxvibration = scxvibrationname;
}
}
}
}
}
You can use PropertiesService to store the last row of the previous script run
The following code sets the start row for the for loop to the (last row+1) of the previous script run, so that only e-mails from newly added rows will be sent:
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
currentsheet = ss.getSheetName();
//var values = ss.getRange(a1Notation)
//console.log(values);
var lastcol = ss.getLastColumn();
var lastrow=ss.getLastRow();
var vibrationtemplate = HtmlService.createTemplateFromFile("vibration");
var temperaturetemplate = HtmlService.createTemplateFromFile("temperature");
//console.log(lastcol);
if(PropertiesService.getScriptProperties().getKeys().length==0){
PropertiesService.getScriptProperties().setProperty('startRow', lastrow+1);
}
var startRow=PropertiesService.getScriptProperties().getProperty('startRow');
if((currentsheet == 'A Vibration') || (currentsheet == 'B Vibration')){
console.log(currentsheet);
//I ASSUME THAT YOU WANT TO LOOP THROUGH ALL ROWS AND NOT COLUMNS
for(var i =startRow; i<=lastrow; i++){
var cell = ss.getRange(i,lastcol).getValues();
console.log(""+cell);
if(cell > 8){
console.log("Value is more than 8 and current value is "+cell);
vibrationtemplate.vibrate = cell;
MailApp.sendEmail("someone#gmail.com",
"Parameter Out of Range Notification",
"",{htmlBody: vibrationtemplate.evaluate().getContent()});
}
}
}
...
PropertiesService.getScriptProperties().setProperty('startRow', lastrow+1);
}
function myFunction() {
const ss = SpreadsheetApp.getActiveSheet();
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sheetNumber = sheets.length; //Get number of sheets within Spreadsheet
var currentSheet = ss.getIndex()-1; //Get index of current sheet with 0 indexing
var vibrationtemplate = HtmlService.createTemplateFromFile("vibration"); //Create HTML for email by grabbing template from vibration.html
var temperaturetemplate = HtmlService.createTemplateFromFile("temperature"); //Create HTML for email by grabbing template from temperature.html
const vibrationlimit = 8; //Set vibrationlimit as constant equals to 8
const temperaturelimit = 80; //Set temperaturelimit as constant equals to 80
var currentDate = new Date(); //Get system Date and Time
var currentDay = currentDate.getDate(); //Extract Date from Full Date(currentDate)
var currentMonth = currentDate.getMonth() +1; //Extract Month from Full Date(currentDate), add +1 as month index start from 0.
for (var z = currentSheet ; z<sheetNumber ; ++z ){
SpreadsheetApp.setActiveSheet(sheets[z])
var lastcol = sheets[z].getLastColumn();
var lastrow= sheets[z].getLastRow();
var cellDate = sheets[z].getRange(1,lastcol).getValues();
var formattedCellDate = new Date(cellDate);
var cellDay = formattedCellDate.getDate();
var cellMonth = formattedCellDate.getMonth() + 1;
if((z==0) || (z==2)){
if((cellDay == currentDay) && (cellMonth == currentMonth)){
for(var i = 2; i<=lastrow; i++){
var scxvibrationname = sheets[z].getRange(i,1).getValues();
var vibration = sheets[z].getRange(i,lastcol).getValues();
if(vibration > vibrationlimit){
Logger.log("Vibration over 8 - Current Value is "+vibration);
vibrationtemplate.vibrate = vibration;
vibrationtemplate.scxvibration = scxvibrationname;
}
}
}
}
}
I manipulated by using daily time-driven trigger.

Script exceeds maximum execution time

I am using a script to first copy a list of all terminated products from "data" tab of the sheet to the "terminated tab"
The data tab looks like below
The code checks if there is an end date written
if it is - the row is copied and pasted in the "terminated" tab
Once all rows (around 2000) are completed
the code the deletes all rows from the "data" tab that have an end date on it
But the code is not very efficient and data is huge - I get a "maximum execution time exceeded" error
function movingTerms() {
var app = SpreadsheetApp ;
var sheet1 = app.getActiveSpreadsheet().getSheetByName("data") ;
var sheet3 = app.getActiveSpreadsheet().getSheetByName("Terminations");
var range1 = sheet1.getRange(2, 1, sheet1.getLastRow() - 1,9);
var range3 = sheet3.getRange(2, 1, sheet3.getLastRow(), 9);
var values1 = range1.getValues();
var values3 = range3.getValues();
var rowcount = sheet1.getLastRow();
var row_deleted = 0;
for (var i = 0; i < (sheet1.getLastRow() - 1); i++)
{
if (values1[i][4] !== "")
{
var rowtodelete = sheet1.getRange(i + 2, 1, 1, 10);
var rowtoadd = sheet3.getRange(sheet3.getLastRow() + 1, 1);
rowtodelete.copyTo(rowtoadd);
}
}
for (var k = 0; k < values1.length; k++)
{
var row = k + 1 - row_deleted;
if (values1[k][4] !== "")
{
var getridof = row +1;
sheet1.deleteRow(getridof);
row_deleted++;
}
}
}
I generally like to see the spreadsheet to do this correctly but this is the way that I would do it.
function movingTerms() {
var ss=SpreadsheetApp.getActive();
var sheet1=ss.getSheetByName("data") ;
var sheet3=ss.getSheetByName("Terminations");
var range1=sheet1.getRange(2, 1, sheet1.getLastRow()-1,9);
var range3=sheet3.getRange(2, 1, sheet3.getLastRow(),9);//You don't really need this
var values1=range1.getValues();
var values3=range3.getValues();//You don't really need this
var rowcount=sheet1.getLastRow();
var rowsdeleted = 0;
for (var i=0;i<values1.length;i++) {
if (values1[i][4]!="") {//column5
var rowtodelete = sheet1.getRange(i-rowsdeleted+2, 1, 1, 10);
var rowtoadd = sheet3.getRange(sheet3.getLastRow()+1,1);//You could also append to sheet 3 if you wish
rowtodelete.copyTo(rowtoadd);
sheet1.deleteRow(i-rowsdeleted+2);
rowsdeleted++;
}
}
}

Apps Script: Loop Function to Submit Active Google Sheet entries to running log sheet in same file?

Looking to loop through the following script to set values in my target sheet for all entries below cell a21 in the 'order entry template' i've created in the 'PO Template' sheet.
function submit() {
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var PONo = activeSheet.getRange("N3").getValue();
var PODate = activeSheet.getRange("N4").getValue();
var SKU = activeSheet.getRange("a22").getValue();
var SKUDesc = activeSheet.getRange("d22").getValue();
var SKUQty = activeSheet.getRange("k22").getValue();
var UtCost = activeSheet.getRange("m22").getValue();
var ExtCost = activeSheet.getRange("p22").getValue();
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
targetSheet.getRange(2, 1).setValue(PONo);
targetSheet.getRange(2, 2).setValue(PODate);
targetSheet.getRange(2, 3).setValue(SKU);
targetSheet.getRange(2, 4).setValue(SKUDesc);
targetSheet.getRange(2, 5).setValue(SKUQty)
targetSheet.getRange(2, 6).setValue(UtCost);
targetSheet.getRange(2, 7).setValue(ExtCost);
}
Here you are! Need to run now, I'll add comments later:
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
// POTemplate range size
// I prefer not having ranges in A1 notation when I'm going to iterate
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
// Get all data at once: less getValue() calls, much faster
var rangeData = tplSheet.getRange(22, 1, tplRowsNum, tplColsNum).getValues();
// Column indexes to filter (A, D, K, M, P)
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
// Set size of destination range in POHistory sheet
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
// Set all values at once
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum, tgtColsNum).setValues(fData);
}
// Function to extract only the columns you need
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
// Transpose Array to get only the column needed
twoDArr = twoDArr.transpose();
for(var i=0; i<indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
// Transpose result Array
return fData.transpose();
}
// Prototype function to transpose a 2D Array
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
};

Changes made in one spreadsheet must get reflected in another spreadsheet

I have a google spreadsheet "shared" where it consists of all the bill of materials. I want to keep another spreadsheet "master" such that only owner can access that. Any data inserted in the shared spreadsheet should get reflected in master spreadsheet, but if we edit shared spreadsheet it should not get reflected in master spreadsheet.
Any help would be appreciated.
Well it depends on what you mean by "changes", but you could put =Master!A1 in cell A1 of the slave sheet, then drag the bottom right corner all the way down, then drag the bottom right corner of that selection all the way across. So cell D8 will have =Master!D8, and so on.
Google Spreadsheets does have a scripting capability. It also has a public gallery script.
image http://img593.imageshack.us/img593/5410/screenshot20110720at736.png
One of the public scripts is edit to another spreadsheet
edit to another spreadsheet
update in another spreadsheet the changes in the current one
ticcaje (at) gmail.com
image http://img97.imageshack.us/img97/240/picture1nns.png
unfortunately it has not been updated in some time, and after looking at the code I don't think it was ever actually completed, as there is a dialog message and then a return statement.
image http://img718.imageshack.us/img718/5264/pictureja.png
I think this could be a really useful script and so I've done a little editing with it, but actually there are no comments in it, and I don't have the time to get it working 100% right now, but I wanted to post it here in hopes that somebody could actually pick it up and run with it.
function onEdit(){
var sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var targetSpreadsheet = SpreadsheetApp.openById('0AntUWac3dtkUac3dtnhTjMwac3dtVjBiac3dtOXcac3dt'); //put in your spreadsheet key here
var sourcesSheet = sourceSpreadsheet.getSheets()[0];
var targetSheet = targetSpreadsheet.getSheets()[0];
var currentSourceCellIndex = SpreadsheetApp.getActiveRange().getRow(); //ActiveCell().getValues();
var selectedCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection().getA1Notation();
var targetRowsCount = targetSheet.getLastRow();
var targetColumns = sourcesSheet.getLastColumn();
var targetRange = targetSheet.getRange(1, 1, targetRowsCount, targetColumns);
var targetSources = targetRange.getValues();
var sourceRows = sourcesSheet.getLastRow();
var sourceColumns = sourcesSheet.getLastColumn();
var sourcesRange = sourcesSheet.getRange(1, 1, sourceRows, sourceColumns);
var sources = sourcesRange.getValues();
var compareName = sources[currentSourceCellIndex-1][0];
return;
//Browser.msgBox("currentSourceCell: "+sources[currentSourceCellIndex-1][0]);return; // ActiveCell()
//Browser.msgBox("currentSourceCell: "+targetRowsCount);
// return;
for (var i = 1; i < targetRowsCount; ++i) {
if (targetSources[i-1][0] == compareName){
targetSheet.deleteRow(i);
break;
}
}
// var sourceRows = sourcesSheet.getLastRow();
// var sourceColumns = sourcesSheet.getLastColumn();
// var sourcesRange = sourcesSheet.getRange(1, 1, sourceRows, sourceColumns);
// var sources = sourcesRange.getValues();
//if ((sources[sourceRows-1][0] == "")||(sources[sourceRows-1][1] == "") ||(sources[sourceRows-1][2] == "") || (sources[sourceRows-1][3] == "") || (sources[sourceRows-1][4] == "") || (sources[sourceRows-1][5] == ""))
//return;
//currentSourceCell = sourceSheet.getActiveCell();
rowToInsert = targetSheet.getLastRow();
targetSheet.insertRowAfter(rowToInsert);
var insertRange = targetSheet.getRange(rowToInsert + 1, 1, 1, targetSheet.getLastColumn());
var kolonnen = [];
var tbText = [];
for (var i = 1; i < 16; ++i) {
kolonnen.push(i);
tbText.push(sources[sourceRows-1][i-1]);
}
//Browser.msgBox("source is: "+tbText);return;
for (j = 0; j < kolonnen.length; j++) {
var zellRange = targetSheet.getRange(rowToInsert+1, kolonnen[j], 1, 1);
zellRange.setValue(tbText[j]);
}
}
The original code can be accessed by editing the script, but if you want it I'll just go ahead and post it here, too:
function onEdito() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {
name: "go",
functionName: "insertRow"
}
// ,
// {
// name: "Build Journal",
// functionName: "collectJournal"
// }
];
ss.addMenu("pastePlus", menuEntries);
}
function onEdit(){
var sourceSpreadsheetName = Browser.inputBox("source spreadsheet");
//var sourceSpreadsheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var files = DocsList.getFilesByType("spreadsheet");
//var files = SpreadsheetApp;
Browser.msgBox("currentSourceCell: " +files);
//var sourceSpreadsheet;
for (var i = 0; i < files.length; ++i) {
var filename = files[i].getName();
if (filename == sourceSpreadsheetName) {
var sourceSpreadsheet = SpreadsheetApp.openById(files[i].getId());
var sheets = sourceSpreadsheet.getSheets();
var sourcesSheet = sheets[1];
break;
}
}
var targetSpreadsheetName = "Probando Script"; //DocsList.getFilesByType("spreadsheet");
//var targetSpreadsheet;
for (var i = 0; i < files.length; ++i) {
var filename = files[i].getName();
if (filename == targetSpreadsheetName) {
var targetSpreadsheet = SpreadsheetApp.openById(files[i].getId());
var sheets = targetSpreadsheet.getSheets();
var targetSheet = sheets[1];
break;
}
}
var currentSourceCellIndex = SpreadsheetApp.getActiveRange().getRow(); //ActiveCell().getValues();
var selectedCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection().getA1Notation();
var targetRowsCount = targetSheet.getLastRow();
var targetColumns = sourcesSheet.getLastColumn();
var targetRange = targetSheet.getRange(1, 1, targetRowsCount, targetColumns);
var targetSources = targetRange.getValues();
var sourceRows = sourcesSheet.getLastRow();
var sourceColumns = sourcesSheet.getLastColumn();
var sourcesRange = sourcesSheet.getRange(1, 1, sourceRows, sourceColumns);
var sources = sourcesRange.getValues();
var compareName = sources[currentSourceCellIndex-1][0];
//Browser.msgBox("currentSourceCell: "+sources[currentSourceCellIndex-1][0]);return;
Browser.msgBox("currentSourceCell: "+targetRowsCount);return;
for (var i = 1; i < targetRowsCount; ++i) {
if (targetSources[i-1][0] == compareName){
targetSheet.deleteRow(i);
break;
}
}
var sourceRows = sourcesSheet.getLastRow();
var sourceColumns = sourcesSheet.getLastColumn();
var sourcesRange = sourcesSheet.getRange(1, 1, sourceRows, sourceColumns);
var sources = sourcesRange.getValues();
//if ((sources[sourceRows-1][0] == "")||(sources[sourceRows-1][1] == "") ||(sources[sourceRows-1][2] == "") || (sources[sourceRows-1][3] == "") || (sources[sourceRows-1][4] == "") || (sources[sourceRows-1][5] == ""))
//return;
//currentSourceCell = sourceSheet.getActiveCell();
rowToInsert = targetSheet.getLastRow();
targetSheet.insertRowAfter(rowToInsert);
var insertRange = targetSheet.getRange(rowToInsert + 1, 1, 1, targetSheet.getLastColumn());
var kolonnen = [];
var tbText = [];
for (var i = 1; i < 16; ++i) {
kolonnen.push(i);
tbText.push(sources[sourceRows-1][i-1]);
}
//Browser.msgBox("source is: "+tbText);return;
for (j = 0; j < kolonnen.length; j++) {
var zellRange = targetSheet.getRange(rowToInsert+1, kolonnen[j], 1, 1);
zellRange.setValue(tbText[j]);
}
}