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.
Related
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);
};
so the task is that I need to highlight or scan for duplicate values in a column BUT for the last say 5 rows, eg if I have the data
1. 1
2. 5
3. 7
4. 2
5. 2
6. 3
7. 4
8. 2
9. 3
so in the end, only 5th,6th,8th and 9th row should be highlighted. I can easily do this using the script over here
function myFunction() {
// List the columns you want to check by number (A = 1)
var CHECK_COLUMNS = [1];
// Get the active sheet and info about it
var sourceSheet = SpreadsheetApp.getActiveSheet();
var numRows = sourceSheet.getLastRow();
var numCols = sourceSheet.getLastColumn();
// Create the temporary working sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = ss.insertSheet("FindDupess");
// Copy the desired rows to the FindDupes sheet
for (var i = 0; i < CHECK_COLUMNS.length; i++) {
var sourceRange = sourceSheet.getRange(1,CHECK_COLUMNS[i],numRows);
var nextCol = newSheet.getLastColumn() + 1;
sourceRange.copyTo(newSheet.getRange(1,nextCol,numRows));
}
// Find duplicates in the FindDupes sheet and color them in the main sheet
var dupes = false;
var data = newSheet.getDataRange().getValues();
data.length;
for (i = data.length-1; i > data.length-4; i--) {
for (j = i-1; j > data.length-6; j--) {
if (data[i].join() == data[j].join()) {
i;
j;
dupes = true;
sourceSheet.getRange(i+1,1,1,numCols).setBackground("red");
sourceSheet.getRange(j+1,1,1,numCols).setBackground("red");
}
}
}
// Remove the FindDupes temporary sheet
ss.deleteSheet(newSheet);
// Alert the user with the results
if (dupes) {
Browser.msgBox("Possible duplicate(s) found and colored red.");
} else {
Browser.msgBox("No duplicates found.");
}
};
Now, what I want to do is that when I add a new row I want the code/formula to run again automatically and select the "now previous 5 rows". Like if I add another row
1. 1
2. 5
3. 7
4. 2
5. 2
6. 3
7. 4
8. 2
9. 3
10. 3
It should now highlight 6th,9th and 10th row. Hopefully, I have made it clear.
P.S I also used this formula
=UNIQUE(FILTER(A:A,ARRAYFORMULA(ROW(A:A)>COUNT(A:A)-5+1)))
But first, it doesn't highlight the rows secondly it doesn't return the duplicate values but all the unique values
you can resolve it without script with just two CF rules:
white background: =SUBTOTAL(3,$A$1:$A1)<=COUNTA(A:A)-5
red background: =COUNTIF(QUERY(A:A,"limit 5 offset "&(COUNT(A:A)-5)),A1)>1
I have been using the following script to move "Finished" columns from one sheet to another:
function onEdit(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(s.getName() == "Sheet1" && r.getColumn() == 15 && r.getValue() ==
"Finished") {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Finished");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).moveTo(target);
s.deleteRow(row);
}
}
Im trying to figure out how to get the script to run even if the sheet has not been opened or edited. Im just not sure how to go about changing it to use a time trigger every minute or so.
There are two aspects to the change to a timed trigger from onEdit.
The first concerns revisions to the code, the second is the trigger details.
Code
The code can't be re-used because the timed trigger doesn't provide the same event details as OnEdit.
In addition, it is possible that several rows might be tagged "Finished" between each trigger event, and the code needs to respond to them all. lastly, each "finished" row can't be deleted as it is found, because this affects the row number of all remaining rows in the column.
The following code would do the job:
Most of it will be familiar to the questioner. The main except is to keep a record of each row number that is moved to "Finished". This is done by pushing the row number onto an array. Then after all data has been examined and moved, there is a small loop that takes the row numbers recorded in the array and deletes the relevant row. The loop works from the highest row number to the lowest; this is so that the deletion of a row does not affect the row number of any remaining rows to be deleted.
function so_53305432() {
// set up the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// identify source and target sheets
var sourceSheet = ss.getSheetByName("Sheet1");
var targetSheet = ss.getSheetByName("Finished");
// get some variables to use as ranges
var sourcelastRow = sourceSheet.getLastRow();
var numColumns = sourceSheet.getLastColumn();
var targetLastRow = targetSheet.getLastRow();
// get data from the Source sheet
var sourceData = sourceSheet.getRange(1, 1, sourcelastRow, numColumns).getValues();
// set up some variables
var finishedRows = [];
var i = 0;
var x = 0;
var temp = 0;
// loop through column 15 (O) checking for value = "Finished"
for (i = 0; i < sourcelastRow; i++) {
// If value = Finished
if (sourceData[i][14] == "Finished") {
// define the target range and move the source row
var targetLastRow = targetSheet.getLastRow();
var target = targetSheet.getRange(targetLastRow + 1, 1);
sourceSheet.getRange(+i + 1, 1, 1, numColumns).moveTo(target);
// keep track of the source row number.
finishedRows.push(i);
}
}
// set up variables for loop though the rows to be deleted
var finishedLength = finishedRows.length;
var startcount = finishedLength - 1
// loop throught the array to delete rows; start with the highest row# first
for (x = startcount; x > -1; x--) {
// get the row number for the script
temp = +finishedRows[x] + 1;
// delete the row
sourceSheet.deleteRow(temp);
}
}
Trigger
The trigger needs to be revised. To do this:
1) Open the script editor, select Current Project Triggers. OnEdit should appear as an existing trigger with an event type of OnEdit.
2) Change "Choose which function to run" to the new function,
3) Change "Select Event Source" from Spreadsheet to "Time Driven".
4) Select "Type of time based trigger" = "Minutes Timer".
5) Select "Select Minute Interval" = , and select a time period and interval.
6) Save the trigger, and then close the Trigger tab
If "Every Minute" is found to be too often, then the Questioner could try "Every 5 minutes".
I have a google spreadsheet that i have one last problem i cant seem to solve.
i added a button to this script, and when i press the button it triggers the AddClient function.
How can i make the script below loop down all rows in column 3 searching for the yes value, when it finds it, copy the row below it to sheet "client" and then stop?
function AddClient(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(s.getName() == "SETUP" && r.getColumn() == 3 && r.getValue() == "yes") {
var row = r.getRow() + 1; // Add 1 to the active row
var targetSheet = ss.getSheetByName("client");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 2, 1, 4).copyTo(target, {contentsOnly:true}); //Only selecting column 2, then the following 4 columns
}
}
Edit*
Example document:
https://docs.google.com/spreadsheets/d/1DFbAp0IN8_UFv9u8kWiZBTxDogj4e7FnuAPzC0grDw0/edit?usp=sharing
Any help greatly appreciated!
Cheers,
Reiel
Since you have a static form the position of the informatin to be copied will not change
Since we know we want to copy over the data we won't need to do any validation of where we are so all of that stuff can go
Sheets have an appendRow method that take care of the bookkeeping involved with finding the last row
This allows us to simplify the script to the following:
function AddClient() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getSheetByName("SETUP").getRange(25, 2, 1, 4).getValues()[0];
ss.getSheetByName("client").appendRow(data);
}
Edit:
To remove duplicates you could do the following:
function AddClient() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getSheetByName("SETUP").getRange(25, 2, 1, 4).getValues()[0];
var clients = ss.getSheetByName("client").getDataRange().getValues();
if (!clients.filter(function(row) {return data.join("|") === row.join("|");})) {
ss.getSheetByName("client").appendRow(data);
}
}
Note that for the particular example there are some problems because the leading zero gets cut off. Sheets is a bit weird and sometimes tries to force the format to be a number even when you set the cells' formats to Text...
I have successfully linked my BigCommerce account to my Google Sheets (Drive) account so every time I receive a new order in my store the order is automatically exported into a Google Sheet. Unfortunately, an entire order is listed on one row with multiple items added into one cell. What I need is to have each product on its own row; for example, if someone orders three different products Zapier would create three new rows. This functionality exists when directly exporting orders from BigCommerce, but the "Zap" does not use the BigCommerce export function when pulling order information from my store to the Google Sheet.
I know this is a shot in the dark, but I am hoping someone might have a solution that I can implement. Thank you for your help!
I have created a script that perhaps could be used or modified, at least until you find if the process can be done within Zapier.
You can try the script in the following ss: https://docs.google.com/spreadsheets/d/1ggNYlLEeN3UYtZC_KlOGwpyII9CzOLKMnIOKIDrPJPM/edit?usp=sharing
The script assumes that orders arrive in the tab named Zapier. As things are set up, you would run the script through the Custom Menu.
If there are 2 orders or more, click the menu for each order.
The complete rows appear in the sheet FullList.
(if you want to play/try again, you will have to manually delete the rows in FullList once they are showing).
function processForNewOrders() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName('Zapier');
var destinationSheet = ss.getSheetByName('FullList');
var sourceValues = sourceSheet.getDataRange().getValues();
var destinationValues = destinationSheet.getDataRange().getValues();
var index = [];
destinationValues.forEach( function (x) {
index.push(x[0]);
})
var newOrders = [];
for (var y = sourceValues.length -1 ; y > 0 ; y --){
if(sourceValues[y][0].toString().indexOf('po_number') != -1 ) continue;
var i = index.indexOf(sourceValues[y][0]);
if(i != -1) break; // This readies only the fresh orders for processing
newOrders.push(sourceValues[y]);
}
Logger.log(newOrders)
for (var j = 0 ; j < newOrders.length ; j++){
var output = [];
var orderLine = newOrders[j];
Logger.log('orderLine = ' + orderLine);
var circuit = 0;
var items = 1
while (circuit < items){
var row = [];
for (var z = 0 ; z < orderLine.length; z++){
var cell = orderLine[z];
// Logger.log(cell);
var lines = cell.toString().split(',');
if(lines.length > 1) items = lines.length;
row.push(lines[circuit] ? lines[circuit] : lines[0]);
// Logger.log('row =' + row);
}
circuit ++;
Logger.log('circuit circuit circuit =' + circuit)
output.push(row);
}
}
Logger.log(output);
if(output != undefined)
destinationSheet.getRange(index.length+1,1,output.length,output[0].length).setValues(output);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Custom Menu')
.addItem('Process new order', 'processForNewOrders')
.addToUi();
}