I iterate through the rows and get the value of a certain cell like so:
for (var i = 2; i < lastRow; i++) {
if (sheet.getRange(i, getColIndexByName("Department Concerned")).getValue() == "HR") {
// Do some stuff
}
}
I copy data to another sheet like so:
// select the Spreadsheets
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("Spreadsheet ID");
// select the Sheets from the Spreadsheets
var source_sheet = ss.getSheetByName("Logs");
var target_sheet = target.getSheetByName("Sheet3");
// select the range from the Sheets
var source_range = source_sheet.getRange("A2:J500");
var target_range = target_sheet.getRange("A2:J500");
// get the values from the source sheet
var values = source_range.getValues();
// set the values to the destination sheet
target_range.setValues(values);
What I need is to copy that data and add it to the same range of the other Spreadsheet depending on the cell value that I just took in my "for loop".
Thank you.
What you think was right, but need to find better approach.
Select values from source sheet
Check each rows, column Department Concerned for "HR" value
Select rows that fulfill above condition
Paste it in target sheet
I combined those scenarios as this,
function myFunction()
{
// select the Spreadsheets
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("Spreadsheet ID");
// select the Sheets from the Spreadsheets
var source_sheet = ss.getSheetByName("Logs");
var target_sheet = target.getSheetByName("Sheet3");
// select the range from the Sheets
var source_range = source_sheet.getRange("A2:J500");
// get the values from the source sheet
var values = source_range.getValues();
// an array for selected rows
var selectedRows = [];
for(var row in values)
{
// thinking 5th column is Department Concerned
if(values[row][4] =='HR')
{
//add add entire row to selected 2d array
selectedRows.push(values[row]);
}
}
// set the values to the destination sheet
target_sheet.getRange(2, 1, selectedRows.length,10).setValues(selectedRows);
}
Related
How can I merge multiple tabs in a Google Spreadsheet using Google App Script ? Data in all the tabs keep changing.
For example, I have 'Sheet1', 'Sheet2' and 'Sheet3' in a Google spreadsheet. Data in all these sheets have 3 columns - Name and email ID & Region. Now, I want to merge/combine the data present in these 3 sheets/tabs into a 4th Sheet i.e. 'Sheet 4' having same Columns (name, email Id & Region). The 4th sheet should have data as - data of Sheet1 followed by Sheet2 and then Sheet3. The number of rows in all the 3 sheets keeps changing.
=query({Sheet1!A1:C; Sheet2!A1:C; Sheet3!A1:C}, "where Col1 is not null", 0)
I wouldn't use a script for this; the worksheet formulas are much faster, at least most of the time.
Make sure you use semicolons to separate the ranges. Semicolons are the End_Of_Row operator for array literals.
If you really want to use a script...
function combineSheets() {
var sApp = SpreadsheetApp.getActiveSpreadsheet();
var s1= sApp.getSheetByName("Sheet1");
var s2= sApp.getSheetByName("Sheet2");
var s3= sApp.getSheetByName("Sheet3");
var s4= sApp.getSheetByName("Sheet4");
// If Sheet4 doesn't exist you'll need to create it here.
var s1values = s1.getRange(1,1,s1.getLastRow(),3).getValues();
var s2values = s2.getRange(1,1,s2.getLastRow(),3).getValues();
var s3values = s3.getRange(1,1,s3.getLastRow(),3).getValues();
// Now, we can put out all together and stuff it in Sheet4
var s4values = [];
s4values = s1values.concat(s2values,s3values);
s4.getRange(1,1,s4values.length,3).setValues(s4values);
}
You don't need a script for this. In the fourth sheet, enter the following formula in A2:
={filter(Sheet1!A2:C, len(Sheet1!A2:A)); filter(Sheet2!A2:C, len(Sheet2!A2:A)); filter(Sheet3!A2:C, len(Sheet3!A2:A))}
It returns the contents of columns A-C where the entry in column A is nonempty, and stacks them in one array.
You can use Google Apps Scripts for this.
var ss = SpreadsheetApp.getActiveSpreadsheet();
function TotalsSheet() {
var totaldata = [];
var sheets = ss.getSheets();
var totalSheets = 2;
for (var i=0; i < totalSheets; i++) {
var sheet = sheets[i];
var range = sheet.getDataRange();
var values = range.getValues();
for (var row in values) {
totaldata.push(values[row]);
}
}
return totaldata;
}
function Start() {
var All = ss.insertSheet("All-Values");
var totaldata = TotalsSheet();
for (var i = 0; i < totaldata.length; i++) {
All.appendRow(totaldata[i]);
}
}
//This Script is must faster
function consolidateData(){
// defined all variables
var sheetNames = [];
var dataSheet = [];
var dataValues = [];
var conso=[];
var header = [["Name","email ID","Region"]];
var ws = SpreadsheetApp.getActiveSpreadsheet();
// get all sheets
var allsheets = ws.getSheets();
for(var s in allsheets){
var sheet = allsheets[s];
sheetNames[s] = sheet.getName();
dataSheet[s] = ws.getSheetByName(sheetNames[s]);
// adding all sheet's data to a single variable
conso = conso.concat(dataSheet[s].getRange("A2:C"+dataSheet[s].getLastRow()).getValues());
}
// writing data into new sheet
var newSheet = ws.insertSheet().setName("Consolidated_Data");
newSheet.getRange("A1:C1").setValues(header);
newSheet.getRange("A2:C"+(conso.length+1)).setValues(conso);
}
I made one that will do nine tabs' consolidation, with more rows and columns.
=filter({{Sheet1!A1:Q500};{Sheet2!A1:Q500};{Sheet3!A1:Q500};{Sheet4!A1:Q500};{Sheet5!A1:Q500};{Sheet6!A1:Q500};{Sheet7!A1:Q500};{Sheet8!A1:Q500};{Sheet9!A1:Q500}},{{Sheet1!A1:A500};{Sheet2!A1:A500};{Sheet3!A1:A500};{Sheet4!A1:A500};{Sheet5!A1:A500};{Sheet6!A1:A500};{Sheet7!A1:A500};{Sheet8!A1:A500};{Sheet9!A1:A500}}<>"")
I'm wondering if it is a way to generalize the initial filter formula so that you can cut and paste in more sheet numbers, so for instance if there were 20 or 30 tabs with 25 columns, could you consolidate that easily into one page?
How can I merge multiple tabs in a Google Spreadsheet using Google App Script ? Data in all the tabs keep changing.
For example, I have 'Sheet1', 'Sheet2' and 'Sheet3' in a Google spreadsheet. Data in all these sheets have 3 columns - Name and email ID & Region. Now, I want to merge/combine the data present in these 3 sheets/tabs into a 4th Sheet i.e. 'Sheet 4' having same Columns (name, email Id & Region). The 4th sheet should have data as - data of Sheet1 followed by Sheet2 and then Sheet3. The number of rows in all the 3 sheets keeps changing.
=query({Sheet1!A1:C; Sheet2!A1:C; Sheet3!A1:C}, "where Col1 is not null", 0)
I wouldn't use a script for this; the worksheet formulas are much faster, at least most of the time.
Make sure you use semicolons to separate the ranges. Semicolons are the End_Of_Row operator for array literals.
If you really want to use a script...
function combineSheets() {
var sApp = SpreadsheetApp.getActiveSpreadsheet();
var s1= sApp.getSheetByName("Sheet1");
var s2= sApp.getSheetByName("Sheet2");
var s3= sApp.getSheetByName("Sheet3");
var s4= sApp.getSheetByName("Sheet4");
// If Sheet4 doesn't exist you'll need to create it here.
var s1values = s1.getRange(1,1,s1.getLastRow(),3).getValues();
var s2values = s2.getRange(1,1,s2.getLastRow(),3).getValues();
var s3values = s3.getRange(1,1,s3.getLastRow(),3).getValues();
// Now, we can put out all together and stuff it in Sheet4
var s4values = [];
s4values = s1values.concat(s2values,s3values);
s4.getRange(1,1,s4values.length,3).setValues(s4values);
}
You don't need a script for this. In the fourth sheet, enter the following formula in A2:
={filter(Sheet1!A2:C, len(Sheet1!A2:A)); filter(Sheet2!A2:C, len(Sheet2!A2:A)); filter(Sheet3!A2:C, len(Sheet3!A2:A))}
It returns the contents of columns A-C where the entry in column A is nonempty, and stacks them in one array.
You can use Google Apps Scripts for this.
var ss = SpreadsheetApp.getActiveSpreadsheet();
function TotalsSheet() {
var totaldata = [];
var sheets = ss.getSheets();
var totalSheets = 2;
for (var i=0; i < totalSheets; i++) {
var sheet = sheets[i];
var range = sheet.getDataRange();
var values = range.getValues();
for (var row in values) {
totaldata.push(values[row]);
}
}
return totaldata;
}
function Start() {
var All = ss.insertSheet("All-Values");
var totaldata = TotalsSheet();
for (var i = 0; i < totaldata.length; i++) {
All.appendRow(totaldata[i]);
}
}
//This Script is must faster
function consolidateData(){
// defined all variables
var sheetNames = [];
var dataSheet = [];
var dataValues = [];
var conso=[];
var header = [["Name","email ID","Region"]];
var ws = SpreadsheetApp.getActiveSpreadsheet();
// get all sheets
var allsheets = ws.getSheets();
for(var s in allsheets){
var sheet = allsheets[s];
sheetNames[s] = sheet.getName();
dataSheet[s] = ws.getSheetByName(sheetNames[s]);
// adding all sheet's data to a single variable
conso = conso.concat(dataSheet[s].getRange("A2:C"+dataSheet[s].getLastRow()).getValues());
}
// writing data into new sheet
var newSheet = ws.insertSheet().setName("Consolidated_Data");
newSheet.getRange("A1:C1").setValues(header);
newSheet.getRange("A2:C"+(conso.length+1)).setValues(conso);
}
I made one that will do nine tabs' consolidation, with more rows and columns.
=filter({{Sheet1!A1:Q500};{Sheet2!A1:Q500};{Sheet3!A1:Q500};{Sheet4!A1:Q500};{Sheet5!A1:Q500};{Sheet6!A1:Q500};{Sheet7!A1:Q500};{Sheet8!A1:Q500};{Sheet9!A1:Q500}},{{Sheet1!A1:A500};{Sheet2!A1:A500};{Sheet3!A1:A500};{Sheet4!A1:A500};{Sheet5!A1:A500};{Sheet6!A1:A500};{Sheet7!A1:A500};{Sheet8!A1:A500};{Sheet9!A1:A500}}<>"")
I'm wondering if it is a way to generalize the initial filter formula so that you can cut and paste in more sheet numbers, so for instance if there were 20 or 30 tabs with 25 columns, could you consolidate that easily into one page?
I have two sheets with unique IDs in one column. I need to make sure whenever a new ID is added in one sheet (Sheet1), it is copied to the last empty row in the other sheet (Sheet2). The IMPORTRANGE won't work as being dynamic any static information added in the other sheet would be irrelevant to the respective ID.
In another thread [1], I got help developing this script that will do exactly that. However, this script will insert the data in the other sheet in Column A. How can I modify the script so I can decide the specific range where I want the script to insert the data (in Sheet 2).
Update: I created this spreadsheet as an example. I'm trying to ensure that the script does the calculation (ie. adding vlaues that are not duplicated in the first available empty row), starting in cel C10 in "Sheet2". It would be also great if I can somehow change that range if I need to: https://docs.google.com/spreadsheets/d/1abESAXFrOHoqRQRNqQGfmAFxlbD10wlprAf1tca4y7o/edit#gid=132361488
Thanks!
function updateSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = "Sheet1";
var destinationSheet = "Sheet2";
var source_sheet = ss.getSheetByName(sourceSheet);
var target_sheet = ss.getSheetByName(destinationSheet);
var lastCol = target_sheet.getLastColumn();
var lastRow = target_sheet.getLastRow();
if (lastRow > 1) { // <--- Added
var r = target_sheet.getRange(2,1, lastRow - 1, lastCol);
r.sort([{column: 1, ascending: true}]);
}
_updateSpreadsheet(source_sheet, target_sheet);
}
function _updateSpreadsheet(source_sheet, target_sheet) {
var last_row = target_sheet.getLastRow();
var source_data = source_sheet.getRange("A4:A" + source_sheet.getLastRow()).getValues(); // <--- Modified
var target_data = target_sheet.getDataRange().getValues();
var resultArray = [];
for (var n = 0 ; n < source_data.length ; n++) { // <--- Modified
var keep = true;
for(var p in target_data) {
if (source_data[n][0] == target_data[p][0]) {
keep = false; break;
}
}
var columnsToKeep = [0];
var tempData = [];
if(keep){
for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])}
resultArray.push(tempData);
}
}
last_row++;
resultArray = resultArray.filter(String); // <--- Added
if(resultArray.length>0){
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
}
[1] Google Script: Append new values in column to another sheet
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length)
.setValues(resultArray);
This line
Takes the sheet stored in the variable target_sheet
Accesses the defined range
Sets values
The syntax to access a range used in your code is getRange(row, column, numRows, numColumns)
whereby the start column is numerical - in your case it's 1 which corresponds to column A.
If you want to modify the start column from A to B:
Just change your range definition from
getRange(last_row,1,resultArray.length,resultArray[0].length)
to
getRange(last_row,2,resultArray.length,resultArray[0].length)
I am trying to copy one column of cells from a spreadsheet to another (append it at the bottom). The code below works, but I was wondering if it's possible to do this without a loop. Is there a faster or more efficient way of doing this?
function CopyToAnotherSheet() {
var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sourceSpreadSheet.getSheets()[0];
var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
var destSheet = destinationSpreadSheet.getSheets()[0];
// Get the contents of a cell in srcSheet
var range = srcSheet.getRange("xposed!A1:A")
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
destSheet.appendRow(values[i]);
}
}
Cheers!
you can use the getRange() method with setValues to setValues() to set the range as the array only.
Refer this documentation for getting a clear idea Document Link
function CopyToAnotherSheet() {
var sourceSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sourceSpreadSheet.getSheets()[0];
var destinationSpreadSheet = SpreadsheetApp.openById('15-vXNpnzSEKzcqhBmJ_D173rwGyM7TOAZE1iL_wsf2A');
var destSheet = destinationSpreadSheet.getSheets()[0];
// Get the contents of a cell in srcSheet
var range = srcSheet.getRange("xposed!A1:A")
var values = range.getValues();
//returns last row of the destination sheet
var lastRow=destSheet.getLastRow();
//starting from the last row, it will apend the array in the column
//getrange(num of row to start from, num of column to start from, number of rows in array to append, num of column in array to append)
destSheet.getRange(lastRow+1, 1, values.length,1).setValues(values);
}
I am trying to get a sheet using a calculated index. I am having a problem but am unsure whether it's a problem converting a float to an integer or if there is a syntax error. What am I getting wrong?
function copySheetValues()
{
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = SpreadsheetApp.getActiveSheet();
//get the source sheet data
var sourceDataRange = sourceSheet.getDataRange();
var sourceSheetValues = sourceDataRange.getValues();
var sourceRows = sourceDataRange.getNumRows();
var sourceColumns = sourceDataRange.getNumColumns();
// get the source sheet index and set the next sheet index
var sourcesheetIndex = sourceSheet.getIndex();
var destinationsheetIndex = Math.round(sourcesheetIndex + 1);
// get the next sheet
var destinationSheet = spread.getSheets()[destinationsheetIndex]
//destination.insertSheet(sourcename, 0);
destinationSheet.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceSheetValues);
}
As getIndex() is 1 based and getSheets() is 0 based you might try:
var destinationSheet = spread.getSheets()[sourceSheet.getIndex()];
go figure
Caveat: getIndex() returns the sheets position within the spreadsheet where getSheets() has to do with the order in which the sheets were added and the two may not correspond if the spreadsheet has been rearranged after the sheets were added.
To insure that the destination sheet is the sheet located just after the source sheet:
// get the source sheet index and set the next sheet index
var destinationsheetIndex = sourceSheet.getIndex() + 1;
// get the next sheet
var sheets = spread.getSheets();
for (var i=0; i<sheets.length; i++) {
if(sheets[i].getIndex() == destinationsheetIndex ) {
var destinationSheet = sheets[i];
break;
};
};