Google sheets How to create a custom function - google-sheets

I have two sheets
Sheet1
and sheet2
What I want to do is one by one copy the values of each row from sheet 1 to sheet 2. whenever one row is copied from sheet1 to sheet2 (i.e values from cell A to F). the cell G2 and H2 (in sheet2) get values ( based on multiple different formulas filter function, pivit tables etc from other sheets ) When I get the updated values in sheet 2 I want to copy the values form G2 and H2 to the respective row back in sheet 1
basically I want to use the sheet2 as a custom function where cell A2, B2, C2, D2, H2, F2 are inputs and cell G2 and H2 are outputs.
I tried using macros but what is required is a combination of both Absolute and Relative referencing and that doesn't seem to be possible
gif of the process I am doing manually

Did it with appscript and menue items
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('AERON')
.addItem('Calculate Single Cabnets', 'menuItem1')
.addSeparator()
.addItem('Calculate Multiple Cabnets', 'menuItem2')
.addToUi();
}
function menuItem2() {
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getSelection();
if(selection.getActiveRange().getA1Notation()==null)
ui.alert('No range selected');
else{
//get the inputs
var sheetname = SpreadsheetApp.getActiveSheet().getName();
// SpreadsheetApp.getUi().alert(sheetname);
var range = SpreadsheetApp.getActiveSpreadsheet().getRange(selection.getActiveRange().getA1Notation());
var input = range.getValues();
var ac = SpreadsheetApp.getActiveSpreadsheet().getActiveRange()
SpreadsheetApp.getUi().alert(ac);
// get sheet name
sheetname = SpreadsheetApp.getActiveSheet().getName()
const numRows = ac.getNumRows();
for (let i=1; i<= numRows;i++ ){
var cell = ac.getCell(i, 1).offset(0, 0,1,6).getA1Notation();
var cell1 = ac.getCell(i, 1).offset(0, 7,1,2).getA1Notation();
// SpreadsheetApp.getUi().alert(cell + " " +sheetname + " " + cell1);
single_row(sheetname, cell, cell1 );
}
SpreadsheetApp.getUi().alert("All values updated")
}
}
function single_row(sheetName, inputRange, outputRange ) {
var fnSheetName = "Main";
var fnInputRange = 'A2:F2';
var fnOutputRange = 'G2:H2';
var input = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getRange(inputRange).getValues();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(fnSheetName).getRange(fnInputRange).setValues(input);
var output = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(fnSheetName).getRange(fnOutputRange).getValues();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getRange(outputRange).setValues(output);
}
This creates a menue item on the top which one by one copies the values to the other sheet then copies the result back

Related

Google App Scripts Copy row and Sort range using custom function

I am using a modified version of this code. Where the goal is to copy/move a row to another sheet based on a dropdown value. I addition when the dropdown value is changed in sheet 2, after the row has been moved the row should be copied back to sheet 1.
I do have some working code, but it breaks the Don't repeat yourself principle, because the code is repeating it self multiple times. That's why I tried to create a custom function moveWhenDone(); where only the targetSheet variable is unique and is passed as a argument.
For some reason, this code does not work when put in the function and I don't understand why?
Another issue I am facing is regarding the sortSheets(); function, both sheet 1 and sheet 2 have a filter on range A:J sorted by column 1. After the row is copied I need the sheets to re-sort to reflect the changes. For some reason this ONLY works on sheet 1, after I edit a cell in the sheet 1. For sheet 2, no sorting, even after a cell edit.
How can both the sheets be re-sorted after the row is copied?
UPDATE
Link to test sheet
function onEdit(event) {
// assumes source data in sheet 1 named ASSIGMNMENTS
// target sheet 2 of move to named DONE
// getColumn with check-boxes is currently set to colu 7
var act = SpreadsheetApp.getActiveSpreadsheet();
var src = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(src.getName() == "ASSIGMNMENTS" && r.getColumn() == 7 && r.getValue() == "Done") {
// Working but breaks the "Don't repeat yourself" principle
/*var row = r.getRow();
var numColumns = src.getLastColumn();
var targetSheet = act.getSheetByName("DONE");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
src.getRange(row, 1, 1, numColumns).copyTo(target);
src.deleteRow(row);*/
var targetSheet = act.getSheetByName("DONE");
moveWhenDone(targetSheet);
} else if(src.getName() == "DONE" && r.getColumn() == 7 && r.getValue() != "Done") {
// Working but breaks the "Don't repeat yourself" principle
/*var row = r.getRow();
var numColumns = src.getLastColumn();
var targetSheet = act.getSheetByName("ASSIGMNMENTS");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
src.getRange(row, 1, 1, numColumns).copyTo(target);
src.deleteRow(row);*/
var targetSheet = act.getSheetByName("ASSIGMNMENTS");
moveWhenDone(targetSheet);
}
sortSheets();
}
// Only work on ASSIGMNMENTS (sheet 1)
function sortSheets() {
SpreadsheetApp.flush();
var acticeSheet = SpreadsheetApp.getActiveSpreadsheet();
acticeSheet.getRange("A2:Z").sort([{column: 1, ascending: true}]);
}
// Do not work when called from onEdit
function moveWhenDone(targetSheet) {
var source = event.source.getActiveSheet();
var row = r.getRow();
var numColumns = source.getLastColumn();
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
source.getRange(row, 1, 1, numColumns).copyTo(target);
source.deleteRow(row);
}
Here are the issues why your code is not working:
You are using event and r variables in your moveWhenDone() function which is not defined. event and r variables are only accessible in onEdit() unless you pass it as an argument to your moveWhenDone()
The reason why your sort function only works on the active sheet is because you used SpreadsheetApp.getActiveSpreadsheet(); which returns a Spreadsheet object. When getRange() is used, it will get the range on the active sheet in your spreadsheet unless you provide the sheet name as part of your A1 Notation (example, "Done!A2:Z")
By the way, I didn't get your point when you mentioned "Don't repeat yourself principle". It somehow contradicts in your statement where "when the dropdown value is changed in sheet 2, after the row has been moved the row should be copied back to sheet 1."
Here is a sample code to move row data from sheet1 to sheet2 and vise-versa including the sorting:
function onEdit(event) {
// assumes source data in sheet 1 named ASSIGMNMENTS
// target sheet 2 of move to named DONE
// getColumn with check-boxes is currently set to colu 7
var act = SpreadsheetApp.getActiveSpreadsheet();
var src = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(src.getName() == "ASSIGMNMENTS" && r.getColumn() == 7 && r.getValue() == "Done") {
// Working but breaks the "Don't repeat yourself" principle
var row = r.getRow();
var numColumns = src.getLastColumn();
var targetSheet = act.getSheetByName("DONE");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
src.getRange(row, 1, 1, numColumns).copyTo(target);
src.deleteRow(row);
sortSheets()
} else if(src.getName() == "DONE" && r.getColumn() == 7 && r.getValue() != "Done") {
// Working but breaks the "Don't repeat yourself" principle
var row = r.getRow();
var numColumns = src.getLastColumn();
var targetSheet = act.getSheetByName("ASSIGMNMENTS");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
src.getRange(row, 1, 1, numColumns).copyTo(target);
src.deleteRow(row);
sortSheets()
}
}
function sortSheets() {
SpreadsheetApp.flush();
var sheetNames = ["ASSIGMNMENTS", "DONE"];
sheetNames.forEach(sheet => {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
sheet.getRange("A2:H").sort([{column: 1, ascending: true}]);
});
}
Modifications done:
I removed moveWhenDone() since I didn't fully understood its purpose to prevent "Don't repeat yourself principle"
Instead of sorting the sheets every time the onEdit() is triggered, I put the sort function when a row was moved to a different sheet.
I modified the sortSheets() to loop specific sheets listed in sheetNames variable. I changed the range to "A2:H" because the sample sheet provided has mismatch in number of columns. (ASSIGNMENTS sheet has columns A-Y, while DONE sheet has columns A-M, Hence range "A2:Z" cannot be used)
Sample Output:
If you really want to make moveWhenDone() work, you can pass the event and r variables in onEdit(). Sample moveWhenDone(targetSheet, event, r).
But keep in mind that if you do that, what will happen is that you will basically move the current row twice to your destination sheet.
Example:
If you changed Assignment 2 to "Done", its succeeding row will also be moved to another sheet. Hence both Assignment 2 and 5 will be moved even if Assignment 5 is not yet "Done"

How to log data into the last row of the specified column instead of all columns?

Currently, my script is logging values in E based on the position of the last input in columns A,B. Is there a way to prevent these gaps?
var sss = SpreadsheetApp.openById('sampleID');
var ss = sss.getSheetByName('Forecast data');
var range = ss.getRange('B126');
const now = new Date();
const data = range.getValues().map(row => row.concat(now));
var tss = SpreadsheetApp.openById('sampleID2');
var ts = tss.getSheetByName('Archived Data');
ts.getRange(ts.getLastRow()+1, 5,1,2).setValues(data);
}
Try something like this:
ts.getRange(getLastRow_(ts, 5) + 1, 5, 1, 2).setValues(data);
Here's a copy of the getLastRow_() function:
/**
* Gets the position of the last row that has visible content in a column of the sheet.
* When column is undefined, returns the last row that has visible content in any column.
*
* #param {Sheet} sheet A sheet in a spreadsheet.
* #param {Number} columnNumber Optional. The 1-indexed position of a column in the sheet.
* #return {Number} The 1-indexed row number of the last row that has visible content.
*/
function getLastRow_(sheet, columnNumber) {
// version 1.5, written by --Hyde, 4 April 2021
const values = (
columnNumber
? sheet.getRange(1, columnNumber, sheet.getLastRow() || 1, 1)
: sheet.getDataRange()
).getDisplayValues();
let row = values.length - 1;
while (row && !values[row].join('')) row--;
return row + 1;
}
An alternative way to find it is via filter().
Code:
// Sample data to be iserted
data = [[2.4, '5/5/2021']]
var tss = SpreadsheetApp.openById(sampleID2);
var ts = tss.getSheetByName('Archived Data');
// get values on column E and filter the cells with values and get their length
var column = ts.getRange("E1:E").getValues();
var lastRow = column.filter(String).length;
ts.getRange(lastRow + 1, 5, 1, 2).setValues(data);
Sample data:
Output:
Note:
This approach is good when column has no blank cells in between. When you skip a cell, it will not calculate the lastRow properly and might overwrite data. But as long as you do not have gaps in your column, then this will be good.
Resource:
Determining the last row in a single column

getRange variable range

I am trying to use a google sheet to rank a list of elements. This list is continually updated, so it can be troublesome to update the list if i already have hundreds of elements ranked and need to rank 10 new ones. Rather than having to re-rank some of the previously ranked elements every time (whether manually or using formulas), i thought it easier to write a macro that would re-rank for me.
1 - element A
2 - element B
3 - element C
new element: element D
For instance if i wanted element D to be ranked 2nd, i would need to change element B to 3 and element C to 4. This is tedious when doing hundreds of elements.
Here is my code so far but I get stuck with the getRange lines. Rankings are in column A.
function RankElements() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var r = s.getActiveCell();
var v1 = r.getValue();
var v2 = v1 + 1
var v3 = v2 + 1
var lastRow = s.getLastRow();
s.getRange(1,v2).setValue(v2);
s.getRange(1,v3).autoFill(s.getRange(1,v3+":"+1,lastRow), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
s.getRange(1,v3+":"+1,lastRow).copyTo(s.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
s.getFilter().sort(1, true);
};
You can do the following:
Iterate through all values in column A.
For each value, check if (1) ranking is equal or below the new one, and (2) it's not the element that is being added.
If both these conditions are met, add 1 to the current ranking.
It could be something like this:
function RankElements() {
const sheet = SpreadsheetApp.getActiveSheet();
const cell = sheet.getActiveCell();
const row = cell.getRow();
const newRanking = sheet.getActiveCell().getValue();
const firstRow = 2;
const columnA = sheet.getRange(firstRow, 1, sheet.getLastRow() - 1).getValues()
.map(row => row[0]); // Retrieve column A values
for (let i = 0; i < columnA.length; i++) { // Iterate through column A values
if (columnA[i] >= newRanking && (i + firstRow) != row) {
sheet.getRange(firstRow + i, 1).setValue(columnA[i] + 1); // Add 1 to ranking
}
}
sheet.getFilter().sort(1, true);
};

Google Sheets - Script to change cell value based on several cells values

I have been searching for a while and trying to work together a script from various answered topics that will allow me to adjust an adjacent cells content based on the data entered. I cannot seem to get it to work properly and need some help steering the ship the right direction. Here is what I am trying to accomplish:
--If the value of cell A2:A is a six digit number AND the value of cell D2:D (same row) is "MATCH" then the value for cell B2:B should be set to "ANN"
--If the value of cell A2:A is a six digit number AND the value of cell D2:D (same row) is "NO MATCH" then the value for cell B2:B should be set to "ANN" and a drop-down data validation list of ['ANN','RNW'] populate WITH the default value of the list set to "ANN"
--If the value of cell A2:A has a length of seven or greater characters then a drop-down data validation list of ['1DY','RNW','NEW'] populate WITH the default value of the list set to "1DY"
Is it even possible to set the value of a data validation cell to a specific, default value? This is important as when the user is entering data they will more than likely accept the default value. If they don't want the default value then they can select a value from the drop-down list.
I built a test sheet which shows the what the sheet should look like when data is filled out in column A and the associated values in column B.
My test is here: https://docs.google.com/spreadsheets/d/1p8sq63S-vSU1FKFLjtr2ZypItN5viXotoZL0Ki2PoQM/edit?usp=sharing
Here is the cobbled together script I was attempting to build (I too find it funny). This is my first attempt to right a Google Script to run on a spreadsheet.
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var aSheet = ss.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
var aRow = aCell.getRow();
//var licenseStatus = aSheet.getRange(aRow, aColumn+9).getValue();
// The row and column here are relative to the range
// getCell(1,1) in this code returns the cell at B2, B2
var licenseTypeCell = aSheet.getRange(aRow, aColumn+1);
if (aColumn == 1 && aSheet.getName() == 'Onsite') {
if (isnumber(aCell) && (len(aCell) <= 6)) {
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['ANN','RNW']).build();
licenseTypeCell.setValue("ANN");
licenseTypeCell.setDataValidation(rule);
} else {
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['1DY','RNW','NEW']).build();
licenseTypeCell.setValue("1DY");
licenseTypeCell.setDataValidation(rule);
}
}
}
Any help/guidance would be greatly appreciated.
You are on the right track, few minor changes. Below you will find some new function to be used in your code.
1) getValue() You get your cell using var aCell = aSheet.getActiveCell() i.e the cell that was edited. But to get the value of the cell you will need to do the following aValue = aCell.getValue()
2) isNaN() To check if the aValue (as determined above) is a number or not. You will use a function called isNaN(aValue). Google script uses javascript platform and hence we need to use functions from javascript. This is different from an inbuilt function you use in a google spreadsheet. It returns True if the value is Not A Number(NAN). Hence, we use a not operator(!) to flip the return value, like so
if(!isNaN(aValue))
3) Number of digits There is no len function in google scripts, hence to determine if the number is 6 digits long you can do the following
if(aValue < 1000000)
Your final code will look something like this:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var aSheet = ss.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
var aRow = aCell.getRow();
//var licenseStatus = aSheet.getRange(aRow, aColumn+9).getValue();
// The row and column here are relative to the range
// getCell(1,1) in this code returns the cell at B2, B2
var licenseTypeCell = aSheet.getRange(aRow, aColumn+1);
var aValue = aCell.getValue()
if (aColumn == 1 && aSheet.getName() == 'Main') {
if (!isNaN(aValue) && aValue < 1000000) {
var matchCell = aSheet.getRange(aRow, aColumn+3).getValue()
//The above gets value of column D (MATCH or NO MATCH)
if(matchCell == "MATCH"){ //Check if Col D is MATCH
licenseTypeCell.setValue("ANN");
}
else{
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['ANN','RNW']).build();
licenseTypeCell.setValue("ANN");
licenseTypeCell.setDataValidation(rule);
}
} else {
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['1DY','RNW','NEW']).build();
licenseTypeCell.setValue("1DY");
licenseTypeCell.setDataValidation(rule);
}
}
}
Also, note the addition of the following lines to check for col D Value
var matchCell = aSheet.getRange(aRow, aColumn+3).getValue()
//The above gets value of column D (MATCH or NO MATCH)
if(matchCell == "MATCH"){ //Check if Col D is MATCH
licenseTypeCell.setValue("ANN");
}

Sequence number for each different value in a colum

I have an Input column with a sequence of two different letters. As result I want to get something like on the picture. This formulas I will use with ARRAYFORMULA to get unlimited count of rows. To get BLOCK № I was trying to use =COUNTIFS($B$2:B2,"N") but it works only if I copy the formula manually down the column, but if I do:
=ARRAYFORMULA(COUNTIFS(($B$2):(B2:B),"N"))
It doesn't work.
How can I replicate the behavior of this function without needed to manually copy it?
I'd recommend writing a script to fill the Block Nos.
I'll assume the topmost letter begins at cell input!A4 and you want the Block Nos from cell input!C5 and below. Go to the menu bar of the spreadsheet and select Script Editor. Then write the following scripts:
//the main function
function writeBlocks() {
var sheet = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName('input');
var numRows = sheet.getLastRow();
var startRow = 4;
var inputCol = 1;
var outputCol = 3;
var block = 0;
//clear old Block Nos
sheet.getRange(startRow, outputCol, numRows - 3, 1)
.clearContent();
//recalculate LastRow in case there are fewer new inputs than old outputs
numRows = sheet.getLastRow();
//get input data
var input = sheet.getRange(startRow, inputCol, numRows - 3, 1)
.getValues;
//write output data
for (var i = 0; i < input.length; i++) {
block += input[i] == "N" ? 1 : 0;
sheet.getRange(startRow + i, outputCol)
.setValue(block);
}
}
//create new menu
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Calculate blocks", functionName: "writeBlocks"});
ss.addMenu("Custom functions", menuEntries);
}
Save it all, refresh the spreadsheet, and there should be a new option on the menu bar. When you select that option, it will clear the old Block Nos and generate new ones based on the current inputs. Hope this helps.

Resources