How to exchange values using temporary 2D array - google-apps-script

I am currently trying to exchange values between two columns (G and H)
The first sheet column G values don't move if they are found in a first column table reference in another sheet.
if they are found in second column table reference,
they have to swap values with the first sheet column H values the same index.
This code works for column G but not for column H. It gives the elements but not in order.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet29'); //au cas ou ca bug
var lr = spreadsheet.getLastRow();
var lc = spreadsheet.getLastColumn();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet29');
var sheet2 = ss.getSheetByName('Tabs of applications and firmwares');
var range1 = sheet1.getRange(2, 7, sheet1.getLastRow(), 9);
var range2 = sheet2.getRange(2, 1, sheet2.getLastRow(), 4);
var values1 = range1.getValues();
var values2 = range2.getValues();
var compteurBon = 0;
var compteurMauvais = 0;
var tempArray1 = [];
for (var i = 0; i < values1.length; i++) {
for (var j = 0; j < values2.length; j++) {
if (values1[i][0] === values2[j][0]) {
compteurBon++;
} else if (values1[i][0] == values2[j][2]) {
compteurMauvais++;
var tempArrayValue1 = values1[i][0];
tempArray1.push(tempArrayValue1);
values1[i][0] = values1[i][1];
values1[i][1] = tempArray1; // here it doesn't take the right value
}
}
}
range1.setValues(values1);
};

Okay, I think your code is in the good direction but it can be simplified. First of all, I understand that we have two sheets (“Sheet 29” and “Tabs of applications and firmwares”), and you want to copy the values from H to G in case G equals B from the second sheet. As I said in my comment, in case you want to just get two columns in the same range, you should use sheetx.getRange(2, col, sheet1.getLastRow(), 2); This last '2' is the number of columns you are getting into the range (G and H, A and B respectively). If we stick to your approach, we will need another tempArray variable:
for (var i = 0; i < values1.length - 1; i++) {
tempArray1.push(values1[i].toString().split(","));
tempArray2.push(values2[i].toString().split(","));
}
What we are doing here is putting the 4 columns in those two arrays. Each one of them is 2D, so tempArray1 contains all the rows from G and H and the same for tempArray2 with A and B. You can access the data with [x][0] and [x][1] respectively.
After this you can just compare the values of temparray1 and temparray2, and write the values from G (temparray[i][1]) to H (temparray[i, 7])
if (tempArray1[i][0] == tempArray2[i][0]) {
compteurBon++;
} else if (tempArray1[i][0] == tempArray2[i][1]) {
sheet1.getRange(i+2 , 7).setValue(tempArray1[i][1]);
}

Related

Query 2 sets of Sheets data & identify discrepancies

I am trying to use Apps Script to query 2 datasets and compare certain columns across them. I am hoping to...
a) identify missing ID values;
b) reconcile differences in other fields, when the ID values match.
INPUT:
Spreadsheet with 2 tabs (tab1, tab2).
The key ID in each B column (Btab1, Btab2)
I want to identify instances where a unique value (B) is in one dataset but not in the other (the rows are not in the same order)
Run a function & push to an output tab if Btab1 is not in tab2 || Btab2 is not in tab1
When a value of B is in both tabs (the majority of the time), I want to identify instances of data discrepancies in a few columns...
For all instances of B, push B and the relevant columns below to the output tab if...
Column M in tab1 doesn't match column E in tab2
Column P in tab1 <> column F in tab2
Column AN tab1 <> Column G tab2
OUTPUT:
tab that displays problem areas in the datasets.
First column is ID Key.
Second column explains the issue via text string
Again, the challenge here is that the values are not sorted the same, and there could be a slight difference in total # rows
function compare() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.insertSheet(1);
ss.getActiveSheet().setName('output');
var sheet1 = ss.getSheetByName('sheet1');
var sheet2 = ss.getSheetByName('sheet2');
var sheet_output = ss.getSheetByName('output');
var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
var output1 = [];
var a1;
var b1;
var h1;
var i1;
var j1;
var m1;
var o1;
var p1;
var an1;
var ao1;
var x;
var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
var output2 = [];
var a2;
var b2;
var c2;
var d2;
var e2;
var f2;
var g2;
var h2;
var y;
/// can i do for(x in range1; y in range2) { all in one function?? If so, what is the proper syntax?
for(x in range1, y in range2) {
a1 = range1[x][0];
b1 = range1[x][1];
h1 = range1[x][7];
i1 = range1[x][8];
j1 = range1[x][9];
m1 = range1[x][12];
o1 = range1[x][14];
p1 = range1[x][15];
an1 = range1[x][39];
ao1 = range1[x][40];
a2 = range2[y][0];
b2 = range2[y][1];
c2 = range2[y][2];
d2 = range2[y][3];
e2 = range2[y][4];
f2 = range2[y][5];
g2 = range2[y][6];
h2 = range2[y][7];
if (
(b1 != b2) ||
(m1 != e2) // etc etc etc
)
{
//push to output
}}
Whilst your syntax for(x in range1, y in range2) will not return an error, it won't give you the desired result neither if the rows are not in the same order
Reason:
During each iteration both x and y will change, e.g. if var range1 = [1,2,3] and var range2 = [4,5,6], your loop will iterate 3 times and the values in your sample loop iterations will be:
iteration
range1[x] = 1 and range2[y] = 4
iteration
range1[x] = 2 and range2[y] = 5
iteration
range1[x] = 3 and range2[y] = 6
In this case you will not retrieve the combination
range1[x] = 1 and range2[y] = 4
or
range1[x] = 2 and range2[y] = 6
and so on.
Instead you need to use two nested for loops, which would iterate through all possible combinations of x and y:
for(x in range1) {
for(y in range2){
...
}
}
Sidenote:
Even if your rows would be in the same order, you still need to be careful. Because for(x in range1) opposed to for(x = 0; x < range1.length; i++) gives you no control about in which folder the loop will iterate over the range.
Now to your query for duplicates
A possible way to implement the functionality in a not too complicated manner would be the following:
Define boolean variable and use it to check for each x either it has a duplicate
If a duplicate (for column B) is found - further criteria will be evaluated
If two rows match by all criteria, the inner loop will be exited with break and the function will jump to the next x
If rows with identical key IDs, but discrepancies in other columns are found - both rows will be pushed into sheet output for comparison purposes (this is easier to implement than specifying what exactly is discrepant)
After this the inner loop will also be exited
In oth cases above duplicate will be set to true
If a unique Id is found in sheet1 (duplicate = false) - it will be immediately pushed into output
Sample
function compare() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.insertSheet(1);
ss.getActiveSheet().setName('output');
var sheet1 = ss.getSheetByName('sheet1');
var sheet2 = ss.getSheetByName('sheet2');
var sheet_output = ss.getSheetByName('output');
var range1 = sheet1.getRange(1,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues();
var output1 = [];
var b1;
var m1;
var p1;
var an1;
var x;
var range2 = sheet2.getRange(1,1,sheet2.getLastRow(),sheet2.getLastColumn()).getValues();
var output2 = [];
var b2;
var e2;
var f2;
var g2;
var y;
var array = [];
for(x in range1) {
var duplicate = false;
for(y in range2){
b1 = range1[x][1];
m1 = range1[x][12];
p1 = range1[x][15];
an1 = range1[x][39];
b2 = range2[y][1];
e2 = range2[y][4];
f2 = range2[y][5];
g2 = range2[y][6];
if (
(b1 == b2)
)
{
Logger.log("found");
duplicate = true;
if((m1 != e2)||
(p1 != f2) ||
(an1 != g2)){
array.push(range1[x]);
array.push(range2[y]);
}
break;
}
}
if (duplicate == false){
Logger.log("duplicate false");
array.push(range1[x]);
}
}
//push to output
if(array[0]){
sheet_output.getRange(sheet_output.getLastRow()+1, 1, array.length, array[0].length).setValues(array);
}
}

Code Error Pop Up inside cell as #DIV/0! after code runs through all cells

I am working on macro scripting where Finance formula is used also inside the worksheet
I am able to receive the result values when there are different values in Row1 but when there are transpose values of Column 1, then I receive Error.
Please see the code below and attached two screenshots also
function MyFunction(){
var sd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SD');
var cr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('CORRELATION');
var lr = cr.getLastRow();//find last row
var lc = cr.getLastColumn();//find last column
var data = cr.getRange(1, 1, lr, lc).getValues();
var data1 = sd.getRange(1, 1, 999,9999).getValues();
var c = 2
for ( var i = 1; i <= lc - 1; i++ ){
var r = 2
for ( var j = 1; j <= lr - 1; j++ ){
//Logger.log(data[0][i] + " - " +data[j][0])
sd.getRange("B1").setValue(data[0][i])
sd.getRange("S1").setValue(data[j][0])
cr.getRange(r, c).setValue(sd.getRange("H8").getValue())//error comes here
r = r + 1
}
c = c+ 1
}
SpreadsheetApp.getActiveSpreadsheet().toast('Task Completed!', 'Status');
}
Picture 01
Picture 02
I'm guessing that you incrementing your column or row outside of the limits of your sheet. Start with the following code and rewrite your function:
function MyFunction(){
var ss=SpreadsheetApp.getActive();
var sd=ss.getSheetByName('SD');
var cr=ss.getSheetByName('CORRELATION');
var data=cr.getRange(1, 1, cr.getLastRow(), cr.getLastColumn()).getValues();
var data1=sd.getRange(1, 1, sd.getLastRow(),sd.getLastColumn()).getValues();
for(var i=0;i<data.length;i++) {
for(var j=0;j<data[i].length;j++) {
}
}
}

Sum up the time values corresponding to same date

In my sheet column A is date and column B is time duration values, I want to find the dates which are repeated and sum up the corresponding time values of the repeated dates and show the sum in the last relevant repeated date. And delete all the other repeated dates. ie if 18/07/2019 is repeated 4 times i have to sum up all the four duration values and display the sum value in the 4th repeated position and delete the first three date 18/07/2019. I have to do this all those dates that are repeated. I have wrote code to my best knowledge
function countDate() {
var data = SpreadsheetApp.getActive();
var sheet = data.getSheetByName("Sheet5");
var lastRow = sheet.getLastRow();
var sh = sheet.getRange('A1:A'+lastRow);
var cell = sh.getValues();
var data= sheet.getRange('B1:B'+lastRow).getValues();
for (var i =0; i < lastRow; ++i){
var count = 0;
var column2 = cell[i][0];
for (var j =0; j < i; j++)
{
var p=0;
var column4 = cell[j][0];
if (column4 - column2 === 0 )
{
var value1 = data[j][0];
var value2 = data[i][0];
var d = value2;
d.setHours(value1.getHours()+value2.getHours()+0);
d.setMinutes(value1.getMinutes()+value2.getMinutes());
sheet.getRange('C'+(i+1)).setValue(d).setNumberFormat("[hh]:mm:ss");
sheet.deleteRow(j+1-p);
p++;
}
}
}
}
The copy of the sheet is shown
column C is the values I obtain through the above code AND column D is the desired value
After computing the sum I need to delete the repeated rows till 15 here
Answer:
You can do this by converting your B-column to a Plain text format and doing some data handling with a JavaScript dictionary.
Code:
function sumThemAllUp() {
var dict = {};
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getLastRow();
var dates = SpreadsheetApp.getActiveSpreadsheet().getRange('A1:A' + lastRow).getValues();
var times = SpreadsheetApp.getActiveSpreadsheet().getRange('B1:B' + lastRow).getValues();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).setNumberFormat("#");
for (var i = 0; i < dates.length; i++) {
if (!dict[dates[i][0]]) {
dict[dates[i][0]] = times[i][0];
}
else {
var temp = dict[dates[i][0]];
var hours = parseInt(temp.split(':')[0]);
var minutes = parseInt(temp.split(':')[1]);
var additionalHours = parseInt(times[i][0].split(':')[0]);
var additionalMinutes = parseInt(times[i][0].split(':')[1]);
var newMinutes = minutes + additionalMinutes;
var newHours = hours + additionalHours;
if (newMinutes > 60) {
newHours = newHours + 1;
newMinutes = newMinutes - 60;
}
dict[dates[i][0]] = newHours + ':' + newMinutes;
}
}
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('A1:B' + lastRow).clear();
var keys = Object.keys(dict);
for (var i = 0; i < keys.length; i++) {
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('A' + (i + 1)).setValue(keys[i]);
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('B' + (i + 1)).setValue(dict[keys[i]]);
}
}
Assumptions I made:
There are a few assumptions I made when writing this, you can edit as needed but I figured I should let you know:
There are only dates in Column A and only times in Column B.
The times in column B are either Hours:Minutes or Minutes:Seconds. Either way, if the value to the right of the : hits 60, it adds one to the left value and resets.
The Sheet within the Spreadsheet is the first sheet; that which is returned by Spreadsheet.getSheets()[0].
References:
w3schools - JavaScript Objects
Spreadsheet.getSheets()
w3schools - JavaScript String split() Method
MDN web docs - parseInt() method
Google Sheets > API v4 - Date and Number Formats

Transpose and Copy to another sheet using Apps script

I need to transpose column data to rows based on the merged header using Apps Script.
Below is the view what would be my input and the expected output,
Input
Output
Sample sheet
What I've written so far:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A1:AO1");
var mergedValues = [];
//get the header added to the array
mergedValues.push(sheet.getRange("A2:I2").getValues());
Logger.log(mergedValues);
var mergedRanges = range.getMergedRanges();
for (var i = 0; i < mergedRanges.length; i++) {
var calcA1Notation = "A"+(i+3) + ":C"+(i+3);
var monA1Notation = "D"+(i+3) + ":F"+(i+3);
//Load the Transpose values into the array
mergedValues.push([[
sheet.getRange(calcA1Notation).getValues().toString(),
mergedRanges[i].getDisplayValue(),
sheet.getRange(monA1Notation).getValues().toString()
]]);
}
Logger.log(mergedValues[0].length);
for (var i = 0; i < mergedValues.length; i++){
//Writes to the lastrow+1 of the sheet
sheet.getRange(sheet.getLastRow()+1, 1).setValue(mergedValues[i]);
}
}
Can you guys help me in modifying google script to generate the expected result?
The question includes the term "Transpose", but this is misleading.
The goal of the questioner is straight-forward; to copy cells from one sheet to another. With one proviso, to include a column header from one sheet as a cell in the target range.
The questioner demonstrated code though they did not explain to what extent this was purposeful. The code takes three columns of data and concatenates the values into a single cell. At best, one might regard this as an early draft.
The referencing of the source data is uncomplicated; getting the month name is the main complication. I used two loops to work through the rows on the Source sheet because the questioner's intended outcome was that the data should sort by month.
I could have built a routine to convert the month string value to a numeric value, then sorted on that value (I certainly thought about it) - but I didn't;)
The Month names are in UPPERCASE, the questioner's outcome uses TitleCase. Again, I could have built a routine to convert the case, and I did spend some time trying. But in the end I decided that it was not a high priority.
function so5273586002() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Declare the two sheets
var sourcesheet = ss.getSheetByName("Input");
var targetsheet = ss.getSheetByName("Output");
// Get the respective starting row and ending rows.'' the target last row is declared in the loop.
var sourcestartrow = 3;
var targetstartrow = 2;
var sourcelastrow = sourcesheet.getLastRow();
// get the the data
var sourcerange = sourcesheet.getDataRange();
var sourcevalues = sourcerange.getValues();
// rubric for copying data.
// each row of the source must create two rows in the target - one row for each month
// the first three columns are repeats on both rows
// each row includes the source data as well as the month name
// target row #1
// source columns A, B & C to target A,B,C
// Month#1; value in D1 Source=> Target Column D (4)
// source columns DEF to target E F G
// target row #2
// source columns A, B & C to target A,B,C
// Month#2: value in G1 Source=> Target D (4)
// source fields G, H I to target E F G
// the questioner's prefered layout is that all the rows are sorted by month; to achive this, I used two loops
// the first to do the first month; the second to do the second month
for (i = sourcestartrow; i < (sourcelastrow + 1); i++) {
// get the last row for the target
var targetlastrow = targetsheet.getLastRow();
// Columns A, B and C -> Columns A, B and C
var targetRange = targetsheet.getRange(targetlastrow + 1, 1); //target: column =A, row = lastrow plus one
var sourcetest = sourcesheet.getRange(i, 1, 1, 3).copyTo(targetRange); // range = active row, column=A, 1 row, 3 columns, copy to SheetTracker
//Logger.log("source range is "+sourcesheet.getRange(i, 1, 1, 3).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 1).getA1Notation());//DEBUG
// Month Name from the header
var targetRange = targetsheet.getRange(targetlastrow + 1, 4); //target: column =D, (month) row = lastrow plus one
var sourcetest = sourcesheet.getRange(1, 4).copyTo(targetRange, {
contentsOnly: true
}); // range = active row, column=A, 1 row, 3 columns, copy to SheetTracker
// Logger.log("source range is "+sourcesheet.getRange(1, 4).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 4).getA1Notation());//DEBUG
// Month details
// Columns D E and F -> Columns E F and G
var targetRange = targetsheet.getRange(targetlastrow + 1, 5); //target: column =E, row = lastrow plus one
var sourcetest = sourcesheet.getRange(i, 4, 1, 3).copyTo(targetRange, {
contentsOnly: true
}); // range = active row, column=D(4), 1 row, 3 columns, copy to SheetTracker
// Logger.log("source range is "+sourcesheet.getRange(i, 4, 1, 3).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 5).getA1Notation());//DEBUG
} // end loop#1
//Loop#2 to generate rows for the second month
for (i = sourcestartrow; i < (sourcelastrow + 1); i++) {
// get the last row for the target
var targetlastrow = targetsheet.getLastRow();
// Columns A, B and C -> Columns A, B and C
var targetRange = targetsheet.getRange(targetlastrow + 1, 1); //target: column =A, row = lastrow plus one
var sourcetest = sourcesheet.getRange(i, 1, 1, 3).copyTo(targetRange); // range = active row, column=A, 1 row, 3 columns, copy to SheetTracker
//Logger.log("source range is "+sourcesheet.getRange(i, 1, 1, 3).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 1).getA1Notation());//DEBUG
// Month Name from the header
var targetRange = targetsheet.getRange(targetlastrow + 1, 4); //target: column =D, (month) row = lastrow plus one
var sourcetest = sourcesheet.getRange(1, 7).copyTo(targetRange, {
contentsOnly: true
}); // range = active row, column=G, 1 row, 3 columns, copy to SheetTracker
//Logger.log("source range is "+sourcesheet.getRange(1, 7).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 4).getA1Notation());//DEBUG
// Month details
// Columns G H and I -> Columns E F and G
var targetRange = targetsheet.getRange(targetlastrow + 1, 5); //target: column =E, row = lastrow plus one
var sourcetest = sourcesheet.getRange(i, 7, 1, 3).copyTo(targetRange, {
contentsOnly: true
}); // range = active row, column=D(4), 1 row, 3 columns, copy to SheetTracker
// Logger.log("source range is "+sourcesheet.getRange(i, 7, 1, 3).getA1Notation()+", target range is "+targetsheet.getRange(targetlastrow + 1, 5).getA1Notation());//DEBUG
} // end loop#2
}
This screenshot shows the Source sheet ("Input").
These screenshots show the Target sheet ("Output") before and after running the code.
UPDATE
As noted in my comments, the earlier draft lacked two things:
1) it was inefficient and followed poor practices because it wrote the value of each field as it was created. The more appropriate approach would have been to write the data to an array, and then copy the array to the target range when the row-by-row processing was complete.
2) the code consisted of two loops to cater for the 2 months in the demonstration data. However, this is an impractical outcome since it is probable that there will be, in reality, any number of months' data in each row. Again, poor practice, when a more appropriate approach was to assume any number of month's data. The more efficient approach would have been to build an array of data while looping through each row.
This revision overcomes both drawbacks.
In addition, since month names do not sort in any meaningful sequence, I added a numeric month id that can be used for filtering and sorting in the output data sheet.
function so5273586003() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Declare the two sheets
var sourcesheet = ss.getSheetByName("Input");
var targetsheet = ss.getSheetByName("Output");
// Get the respective starting row and ending rows.'' the target last row is declared in the loop.
var targetstartrow = 2;
var sourcestartrow = 2;
var sourcelastrow = sourcesheet.getLastRow();
var sourcelastcolumn = sourcesheet.getLastColumn();
//Logger.log("the last row is "+sourcelastow+", and the last column is "+sourcelastcolumn);
// get the the data
var sourcerange = sourcesheet.getDataRange();
var sourcevalues = sourcerange.getValues();
var sourcelength = sourcevalues.length;
var i = 0;
var m = 0;
var month = 1;
var dataarray = [];
var masterarray = [];
// start loop by row
for (i = sourcestartrow; i < (sourcelastrow); i++) {
// start loop by month (within row)
for (m = 0; m <= (sourcelastcolumn - 6); m = m + 3) {
dataarray = [];
// add first three columns
dataarray.push(sourcevalues[i][0]);
dataarray.push(sourcevalues[i][1]);
dataarray.push(sourcevalues[i][2]);
//add the month name
dataarray.push(sourcevalues[0][3 + m]);
//add month data
dataarray.push(sourcevalues[i][3 + m]);
dataarray.push(sourcevalues[i][4 + m]);
dataarray.push(sourcevalues[i][5 + m]);
//create month id
switch (sourcevalues[0][3 + m]) {
case "JULY":
month = 1;
break;
case "AUGUST":
month = 2;
break;
case "SEPTEMBER":
month = 3;
break;
case "OCTOBER":
month = 4;
break;
case "NOVEMBER":
month = 5;
break;
case "DECEMBER":
month = 6;
break;
case "JANUARY":
month = 7;
break;
case "FEBRUARY":
month = 8;
break;
case "MARCH":
month = 9;
break;
case "APRIL":
month = 10;
break;
case "MAY":
month = 11;
break;
case "JUNE":
month = 12;
break;
default:
month = 100;
break;
} // end switch
// add the month id to the array (used for sorting)
dataarray.push(month);
// add the data to the master array before zeroing for next month
masterarray.push(dataarray);
} // months loop
} // end row loop
// get the length of the master array
var masterlength = masterarray.length;
// define the target range
var TargetRange = targetsheet.getRange(targetstartrow, 1, masterlength, 8);
// set the array values on the Target sheet
TargetRange.setValues(masterarray);
}

Copy row values to a new sheet if it exist in another sheet

I am new to Google Script and I have a script to create. I found this question, where in he should delete row if a value in it exists in another sheet. Now, my situation is different. Here is my sample Spreadsheet. In that Google Spreadsheet, I have 3 sheets. The unique value that will be compared on the first 2 sheets is the first column, "ID NUMBER".
Given the values, 784 | John Steep | I.T Department exists in the first 2 sheets therefore the whole row should be copied to sheet3.
Sum up, if that ID NUMBER exists in Sheet 1 and 2, it should be copied on Sheet 3.
I tried to modify the script but I can't make it work:
function copyRowtoSheet3() {
var s1 = SpreadsheetApp.openById("1RlQTLZyPLasoJGplKemKg9qgcLcvCZZ_tPn6lWXEePw").getSheetByName('Sheet1');
var s2 = SpreadsheetApp.openById("1RlQTLZyPLasoJGplKemKg9qgcLcvCZZ_tPn6lWXEePw").getSheetByName('Sheet2');
var s3 = SpreadsheetApp.openById("1RlQTLZyPLasoJGplKemKg9qgcLcvCZZ_tPn6lWXEePw").getSheetByName('Sheet3');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n in values1){
var keep = true
for(var p in values2){
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
keep=false ; break ;
}
}
if(keep){
resultArray.push(values1[n])};
}
s1.clear()
s1.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Thanks. Any help/advice is greatly appreciated.
Not sure your condition works... Getting the values that are equal in both sheets is easier than the example you refer to, just keep the data where equality==true.
Try like this (change the ID's to yours):
function copyRowtoSheet3() {
var s1 = SpreadsheetApp.openById("1x8buwr______w7MeqZAiJJIX0yC-oITBAtykBAM").getSheetByName('Sheet1');
var s2 = SpreadsheetApp.openById("1x8buwr______w7MeqZAiJJIX0yC-oITBAtykBAM").getSheetByName('Sheet2');
var s3 = SpreadsheetApp.openById("1x8buwr______w7MeqZAiJJIX0yC-oITBAtykBAM").getSheetByName('Sheet3');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n=0; n < values1.length ; n++){
var keep = false;
for(var p=0; p < values2.length ; p++){
Logger.log(values1[n][0]+' =? '+values2[p][0]);
if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
resultArray.push(values1[n]);
Logger.log('true');
break ;// remove this if values are not unique and you want to keep all occurrences...
}
}
}
s3.getRange(+1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
Try:
var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 1');
var s2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 2');
var s3 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 3');
and further:
s3.clear()
s3.getRange(1,1,resultArray.length,resultArray[0].length).setValues(resultArray);