Add an answer to the spreadsheet if a script error occurs - google-apps-script

I haven't learned how to adjust so that if there is an error in the script when trying to capture data from openweathermat.org, the word ERROR is written in cell A10 on the Clima page of my spreadsheet.
I would like help and advice on how I should adjust the script to make this happen.
function TudoCompleto() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Clima');
var rg=sh.getRange("B12");
var vA=rg.getValues();
if (vA[0][0]=="OK"){
var spreadsheet = SpreadsheetApp.getActive();
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Clima");
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var cityName = sheet.getRange("A1").getValue();
var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + cityName +"&appid=" + apiKey;
var response = UrlFetchApp.fetch(apiCall);
var data = JSON.parse(response.getContentText());
Logger.log(response.getContentText());
var weather = data["weather"][0]; //It's an array
var sys = data["sys"];
var main = data["main"]
var location = data["name"];
var country = sys["country"];
var weatherDesc = weather["main"];
var temp = main["temp"];
var minTemp = main["temp_min"];
var maxTemp = main["temp_max"];
var weatherData = [
["Location:", location],
["Country:", country],
["Weather:", weatherDesc],
["Teaperture:", temp],
["Min Temp:", minTemp],
["Max Temp:", maxTemp]
];
sheet.getRange(3, 1, weatherData.length, weatherData[0].length).setValues(weatherData);
//The API Call works
// The Data will be retrieved like below JSON file.
//{"coord":{"lon":139,"lat":35},
//"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
//"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
//"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
//"wind":{"speed":7.31,"deg":187.002},
//"rain":{"3h":0},
//"clouds":{"all":92},
//"dt":1369824698,
//"id":1851632,
//"name":"Shuzenji",
//"cod":200}
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 2; i++) {
var cel = "F"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "R"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("R"+u).setValue(sheet.getRange(cel).getValue());
break;
};
}
}
};
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 2; i++) {
var cel = "B"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "S"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("S"+u).setValue(sheet.getRange(cel).getValue());
break;
};
}
}
};
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 10; i++) {
var cel = "H"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "M"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("M"+u).setValue(sheet.getRange(cel).getValue());
break;
};
}
}
};
spreadsheet.getRange('Clima!A12').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
spreadsheet.getRange('Clima!R:S').activate();
spreadsheet.getRange('Clima!I:J').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};
};
In order to publish, I had to add the entire script at the request of a member to help him understand my need. I apologize for the long script.

function TudoCompleto() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Clima');
var rg=sh.getRange("B12");
var vA=rg.getValues();
try{
if (vA[0][0]=="OK"){
var spreadsheet = SpreadsheetApp.getActive();
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Clima");
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var cityName = sheet.getRange("A1").getValue();
var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + cityName +"&appid=" + apiKey;
var response = UrlFetchApp.fetch(apiCall);
var data = JSON.parse(response.getContentText());
Logger.log(response.getContentText());
var weather = data["weather"][0]; //It's an array
var sys = data["sys"];
var main = data["main"]
var location = data["name"];
var country = sys["country"];
var weatherDesc = weather["main"];
var temp = main["temp"];
var minTemp = main["temp_min"];
var maxTemp = main["temp_max"];
var weatherData = [
["Location:", location],
["Country:", country],
["Weather:", weatherDesc],
["Teaperture:", temp],
["Min Temp:", minTemp],
["Max Temp:", maxTemp]
];
sheet.getRange(3, 1, weatherData.length, weatherData[0].length).setValues(weatherData);
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 2; i++) {
var cel = "F"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "R"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("R"+u).setValue(sheet.getRange(cel).getValue());
break;
}
}
}
}
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 2; i++) {
var cel = "B"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "S"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("S"+u).setValue(sheet.getRange(cel).getValue());
break;
}
}
}
}
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // planilha ativa
var sheet = spreadsheet.getSheetByName("Clima");
for (var i = 1; i < 10; i++) {
var cel = "H"+ i //
if (sheet.getRange(cel).getValue() != "") {
for (var u = 1; i < 2000; u++) {
var cel2 = "M"+ u //
if (sheet.getRange(cel2).getValue() == "") {
sheet.getRange("M"+u).setValue(sheet.getRange(cel).getValue());
break;
}
}
}
}
spreadsheet.getRange('Clima!A12').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
spreadsheet.getRange('Clima!R:S').activate();
spreadsheet.getRange('Clima!I:J').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
}
catch(e) {
ss.getSheetByName("Clima").getRange('A10').setValue('ERROR');
Logger.log(e);
}
}

Related

Google Sheet : The result could not be auto-expanded. Please insert new columns (1)

This script import opportunities that we get. It populates rows which then calculates some numbers such as interest and stuff. However, I now have errors when populating my cells (#REF error, see pictures below). Nothing has changed so my first guess is it has do with the processing of the sheet which has become too heavy.
`
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createAddonMenu();
menu.addItem('Créer étude', 'init');
menu.addToUi();
}
function init() {
ss = SpreadsheetApp.getActiveSpreadsheet();
identifyJe();
sheetMaker = ss.getActiveSheet();
currentRow = ss.getActiveCell().getRowIndex();
ssEtudes = SpreadsheetApp.openById(getSheetEtudesId());
var ui = SpreadsheetApp.getUi();
var respon se = ui.alert(
'Ligne sélectionnée : ' + currentRow + '. Exécuter ?',
ui.ButtonSet.OK_CANCEL
);
if (response !== ui.Button.OK) return;
doEtude();
doContrat();
doPhases();
}
function doEtude(nomEtude) {
var etudeData = [];
for (var i = 0; i < etudeNamedRanges.length; i++) {
var column = ss.getRangeByName(etudeNamedRanges[i]).getColumn();
etudeData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('etudes');
var rowToAppend = getFirstEmptyRow(destSheet, 0);
for (var i = 0; i < etudeData.length; i++) {
var column = ssEtudes.getRangeByName(etudeNamedRanges[i]).getColumn();
destSheet.getRange(rowToAppend, column).setValue(etudeData[i]);
}
}
function doContrat() {
var contratData = [];
for (var i = 0; i < contratNamedRanges.length; i++) {
var column = ss.getRangeByName(contratNamedRanges[i]).getColumn();
contratData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('contrats');
var rowToAppend = getFirstEmptyRow(destSheet, 11);
for (var i = 0; i < contratData.length; i++) {
destSheet.getRange(rowToAppend, i + 4).setValue(contratData[i]);
}
}
function doPhases() {
var phasesCoords = getPhasesCoords();
var phasesData = [];
for (var i = 0; i < phasesCoords.length; i++) {
var phaseData = getPhaseData(phasesCoords[i]);
phaseData.unshift(i + 1);
phasesData.push(phaseData);
}
var destSheet = ssEtudes.getSheetByName('phases');
var rowToAppend = getFirstEmptyRow(destSheet, 9);
var columns = [];
for (var nPhase = 0; nPhase < phasesData.length; nPhase++) {
var phaseData = phasesData[nPhase];
for (var i = 0; i < phaseData.length; i++) {
if (columns[i] === undefined)
columns[i] = ssEtudes.getRangeByName(phasesNamedRanges[i]).getColumn();
destSheet
.getRange(rowToAppend + nPhase, columns[i])
.setValue(phaseData[i]);
}
}
}
`
Type of formula
The results
The error, which translates into The result could not be auto-expanded. Please insert new columns (1).
The results actually appear for some time and disappear after a few seconds, constantly. Does it have something to do with the size of the spreadsheet ?

Using Dropdown lists on all sheets in a workbook

I have a dropdown list that is in my workbook in the first tab (Tab titled: Reference Don't Edit) and I have a schedule template (aptly titled "Schedule Template").
I am trying to make the dropdown lists on all of the subsequent tabs (which would be daily tabs) instead of creating a new workbook everyday. I tried changing the dropSS and dropSS_ from using a sheet name to SpreadsheetApp.getActiveSpreadsheet().getSheets() and .getSheet(), etc for use on all active sheets, but it just erases the working dropdown and doesn't put it on the other sheets.
function createPrimaryDrpdwon() {
var dataSS = "References *Don't Edit*";
var dropSS = "Schedule Template";
var primaryDataRange = "A1:A46";
var primaryDropRange = "H4:H";
var primaryDropList = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dataSS).getRange(primaryDataRange).getValues();
var primaryDropRange = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(primaryDropRange);
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(primaryDropList).build();
primaryDropRange.setDataValidation(validationRule);
}
function createSecondaryDrpdwon(e){
var dataSS = "References *Don't Edit*";
var dropSS = "Schedule Template";
var dropSS_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dropSS);
var allDataRange = "A1:B46";
var primaryDDCol = 8;
var dropDData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(dataSS).getRange(allDataRange).getValues();
var activeCell = dropSS_.getActiveCell();
var activeColumn = activeCell.getColumn();
var activeRow = activeCell.getRow();
if(activeColumn==primaryDDCol){
var dep_Col = primaryDDCol+1;
var dep_Row = activeRow;
var depCell = dropSS_.getRange(dep_Row, dep_Col);
var primarySelected = activeCell.getValue();
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(getDependentList(dropDData,primarySelected)).build();
depCell.setDataValidation(validationRule);
}
}
function getDependentList(dropDData,primarySelected){
var dependenList = [];
var j = 0;
if(dropDData != null){
for(i=0; i<dropDData.length; i++){
if(dropDData[i][0]==primarySelected){
dependenList[j] = dropDData[i][1];
j++;
}
}
}
return dependenList;
}
Try this:
function createPrimaryDrpdwon() {
var dataSS = "References *Don't Edit*";
var dropSS = "Schedule Template";
var primaryDataRange = "A1:A46";
var primaryDropRange = "H4:H";
const ss = SpreadsheetApp.getActive();
var primaryDropList = ss.getSheetByName(dataSS).getRange(primaryDataRange).getValues().map(r => r[0]).filter(e => e);
var primaryDropRange = ss.getActiveSheet().getRange(primaryDropRange);
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(primaryDropList).build();
primaryDropRange.setDataValidation(validationRule);
}
function getDependentList(dropDData, primarySelected) {
var dependenList = dropDData.map(r => {
if (r[0] == primarySelected) {
return r[1];
} else {
return '';
}
}).filter(e => e);
return dependenList;
}

Creating sheets with from master sheet

I have a sheet named form responses which gets input from google
forms,Then I created sheets with names from Column C which is
employee code and append all the respective rows from form responses
to the newly created sheets.
Now I have sheets with name as employee code ( which is in column c of the sheet). Then I want to create secondary sheets from this master sheet(sheets with name as employee code) whose name is using the column E value as attached to the Employee code.for eg : if Emp code is 10003825 and value in column E is ASR, the sheet name should be 10001515ASR.
In Column E there are only 4 values ADC,ASR ACC,RSR. let the master sheet(sheets with name as employee code) retain ADC rows always while when other rows containing ASR,ACC,RSR comes append the respective row to the newly created sheet(ie if ASR the row goes to 10001515ASR).
I have shown my present sheet and expected output
The code I developed is shown below:
function switchSheet(){
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheets = activeSpreadsheet.getSheets();
for (var i = 1; i < sheets.length; i++) {
var p = sheets[i].getSheetName();
sheetCreateChannel(p);
}
}
function sheetCreateChannel(ss){
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = activeSpreadsheet.getSheetByName(ss);
var getNames = sheet1.getDataRange().getValues();
getNames.shift();
var sheets = activeSpreadsheet.getSheets();
var sheetsObj = {};
for (var i = 0; i < sheets.length; i++) {
sheetsObj[sheets[i].getSheetName()] = sheets[i];
for (var i = 0; i < getNames.length; i++) {
var r = getNames[i];
if (r[4].toString()== "ASR"&& !((ss+(r[4])) in sheetsObj)) {
var newSheet = activeSpreadsheet.insertSheet(ss + "ASR");
sheetsObj[ss+"ASR"] = newSheet;
}
else if (r[4].toString()== "ACC"&&!((ss+(r[4])) in sheetsObj)) {
var newSheet = activeSpreadsheet.insertSheet(ss + "ACC");
sheetsObj[ss+"ACC"] = newSheet;
}
else if (r[4].toString()== "RSR"&& !((ss+(r[4])) in sheetsObj)) {
var newSheet = activeSpreadsheet.insertSheet(ss + "RSR");
sheetsObj[ss+"RSR"] = newSheet;
}
else {
break;
}
}
}
var deleteRows = 0;
for (var i = 0; i < getNames.length; i++) {
var r = getNames[i];
if (r[4].toString() != "") {
if ((ss+(r[4])) in sheetsObj) {
var Q =ss+(r[4]);
sheetsObj[Q].appendRow(r);
}
deleteRows = i + 2;
}
}
sheet1.getRange(2, 1, deleteRows - 1, sheet1.getLastColumn()).clearContent();
}
This code works fine for my above issue
function sheetCreate(){
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = activeSpreadsheet.getSheetByName("Form Responses 1");
var getNames = sheet1.getDataRange().getValues();
getNames.shift();
var sheets = activeSpreadsheet.getSheets();
var sheetsObj = {};
for (var i = 0; i < sheets.length; i++) {
sheetsObj[sheets[i].getSheetName()] = sheets[i];
}
var deleteRows = 0;
for (var i = 0; i < getNames.length; i++) {
var r = getNames[i];
var N=r[2].toString()+r[4].toString();
if (N != "") {
if (N in sheetsObj) {
sheetsObj[N].appendRow(r);
} else {
var newSheet = activeSpreadsheet.insertSheet((N));
var cell1 = newSheet.getRange("A1").setValue("Timestamp");
var cell2 = newSheet.getRange("B1").setValue("Score");
var cell3 = newSheet.getRange("C1").setValue("Employee ID");
var cell4 = newSheet.getRange("D1").setValue("Name of the ATCO");
var cell5 = newSheet.getRange("E1").setValue("The channel on which duty is performed ");
var cell6 = newSheet.getRange("F1").setValue("DATE on which duty is performed");
var cell7 = newSheet.getRange("G1").setValue("Total duration of duty done");
newSheet.appendRow(r);
sheetsObj[N] = newSheet;
}
deleteRows = i + 2;
}
}
sheet1.getRange(2, 1, deleteRows - 1, sheet1.getLastColumn()).clearContent();
}

First cell in active row during script execution

I am using the code below to view through a sheet, and change the first cell background to red if any other cells are red. What I would like, is to change the first cell in each row to red, only if that row contains a red cell. This code works through the spreadsheet, but only makes cell A1 red. How do I get it to affect the first cell of each row independently?
function MakeRed(){
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var first_column = "B";
var first_row = 1;
var last_row = sheet.getLastRow();
var last_column = sheet.getLastColumn();
var active_row = 1;
var range_input = sheet.getRange(1,1,last_row,last_column);
var range_output = sheet.getRange("A1");
var cell_colors = range_input.getBackgroundColors();
var color = "#ff0000";
var count = 0;
for(var r = 0; r < cell_colors.length; r++) {
for(var c = 0; c < cell_colors[0].length; c++) {
if(cell_colors[r][c] == color) {
count++;
range_output.setBackground("#ff0000");
} else {
count--;
if (count == 0) {
range_output.setBackground("#ffffff");
}
}
}
}
}
I would suggest you do the whole stuff in the array of background colors you already have instead of calling a spreadsheet service each time the condition is true.
Code becomes simpler because I used the indexOf array method in the condition
function MakeRed(){
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var first_column = "B";
var first_row = 1;
var last_row = sheet.getLastRow();
var last_column = sheet.getLastColumn();
var active_row = 1;
var range_input = sheet.getRange(1,1,last_row,last_column);
var range_output = sheet.getRange("A1");
var cell_colors = range_input.getBackgroundColors();
var color = "#ff0000";
var count = 0;
for(var r = 0; r < cell_colors.length; r++) {
Logger.log(cell_colors[r].indexOf(color));// just to check, you can remove this of course ...
if(cell_colors[r].indexOf(color)>-1) {
count++;
cell_colors[r][0]=color;
} else {
count--;
if (count == 0) {
cell_colors[r][0]="#ffffff";
}
}
}
range_input.setBackgroundColors(cell_colors);// update sheet colors
}
EDIT : I don't really understand the idea behind the "count" thing... it works the same way without it (code below) :
function MakeRed(){
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var first_column = "B";
var first_row = 1;
var last_row = sheet.getLastRow();
var last_column = sheet.getLastColumn();
var active_row = 1;
var range_input = sheet.getRange(1,1,last_row,last_column);
var range_output = sheet.getRange("A1");
var cell_colors = range_input.getBackgroundColors();
var color = "#ff0000";
for(var r = 0; r < cell_colors.length; r++) {
Logger.log(cell_colors[r].indexOf(color))
if(cell_colors[r].indexOf(color)>-1) {
cell_colors[r][0]=color;
} else {
cell_colors[r][0]="#ffffff";
}
}
range_input.setBackgroundColors(cell_colors);// update sheet colors
}
edit 2 : this version will reset col A to white if no other red cell is in the row
function MakeRed(){
var book = SpreadsheetApp.getActiveSpreadsheet();
var sheet = book.getActiveSheet();
var first_column = "B";
var first_row = 1;
var last_row = sheet.getLastRow();
var last_column = sheet.getLastColumn();
var active_row = 1;
var range_input = sheet.getRange(1,1,last_row,last_column);
var range_output = sheet.getRange("A1");
var cell_colors = range_input.getBackgroundColors();
var color = "#ff0000";
for(var r = 0; r < cell_colors.length; r++) {
var rowWoColA = cell_colors[r].slice(1);
if(rowWoColA.indexOf(color)>-1) {
cell_colors[r][0]=color;
} else {
cell_colors[r][0]="#ffffff";
}
}
range_input.setBackgroundColors(cell_colors);// update sheet colors
}
Change var range_output = sheet.getRange("A1"); to the range you want edit.
You could do this in the loop:
for(var r = 0; r < cell_colors.length; r++) {
for(var c = 0; c < cell_colors[0].length; c++) {
if(cell_colors[r][c] == color) {
count++;
// Assuming you only want to change bg color of the first column on each row
sheet.getRange(r,1).setBackground("#ff0000");
} else {
count--;
if (count == 0) {
sheet.getRange(r,1).setBackground("#ffffff");
}
}
}
}

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]);
}
}