Create Unique ID from 0 to Upward Google Sheets - google-apps-script

I have a sheet where data is being added to the last empty row and inserting the new row between the rows which has already data.
I want to create a Unique Numeric number that will be 0 to upward in sequence. Like we use =IF(B3<>"",B2+1,"").
But when new row is added the formula is missed I want to Add unique number for each row.
Because when you insert the row all values are bonded but when you type anything in newly added row in Col B all the number goes disturb. It should work like timestamp once a number is allotted to specific row data it should not change even new row is inserted within data.
For example If script has assigned number 1 to 7 and new row inserted then it should assign new row a number 8 even new row is inserted with data in col B
Your help will be appreciated

ALTERNATIVE SUGGESTION
If I have understood your goal correctly, you may try this custom script below that you can copy and paste as a bound script to your Spreadsheet file:
UPDATED Script
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getRange("B2:B").getValues().filter(String); //Add the range where data you want to have IDs, on my end, it's B2 and below (B2:B)
var ids = [];
var lastRow;
for(row=0; row<=data.length-1; row++){
ids.push([row]);
}
lastRow = ids.length + 1;
ss.getRange("A2:A"+lastRow).setValues(ids);
}
SAMPLE DEMONSTRATION
The custom function will add IDs starting on the cell A2 and below once you run it for the first time from the Apps Script editor:
When new added data on cell B10 has been entered:

In the top row,
=ARRAYFORMULA({"ID";SEQUENCE(COUNTA(B:B)+0)})
Change 0 to 1 or 2, if you want some blank row offset.

Related

how to get a row number in a column if a cell in another column has some data using google apps script?

i have a sheet that have 5 columns (date , id , name , number ,row number) and i want the fifth column(row number) to be auto filled with the row number when i insert any data in the second column(id)
i tried the manual way from the sheet itself not apps script but sometimes it gets deleted by mistake so i want to do it with apps script and im not sure if there is a way or not so please help me with it. here is what i mean in example:
first row got headers (date, id , name , number , row number)
lets say i insert in the fifth row some data (today , 4 , ahmed , 4584231 , X)
I WANT WHEN I INSERT THE ID(4), THE ROW NUMBER GETS VALUE (5) AUTOMATICALLY BECAUSE ITS IN THE FIFTH ROW, THEN AFTER THAT LETS SAY I REMOVED ROW NUMBER 3 I WANT ALL THE VALUES IN THE ROW NUMBER COLUMN TO BE CHANGED TO THE NEW ROW IT GOT IN, I HOPE THAT WAS CLEAR FOR YOU.
thank you very mush
This is possible via formula:
IF not blank
Insert this formula in the row number column:
=if(B2<>"",row(),"")
Result:
Just drag/copy the formula down to the column.
This checks if the cell in column B is blank. If not, insert the row number.
ArrayFormula - this is most likely what you need to be safe from accidental deletions
Or you can also use arrayFormula so you only need to insert the formula on the first row after the header and it will be applied to the whole column:
=arrayformula(if(B2:B <> "", row(B2:B), ""))
This can also help you prevent accident deletions. It will reinsert the value on the cell when deleted, just make sure not to delete the actual arrayformula on the cell E2.
Also check that the cells below are empty or it will throw an error.
Result:
USING APPS SCRIPT
function onEdit(e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
var row = r.getRow();
var column = 6;
if (r.getColumn() == 2) {
if (!e.value){
ss.getRange(row,column).clearContent();
}
else {
ss.getRange(row,column).setValue(row);
};
};
};
References:
IF Function - Not blank
ArrayFormula

1:Update from Sheet 1 static row to MasterSheet dynamic row 2:Show & Hide columns and rows base on cell value

SHEET 1
A: I want to update changes to my "MasterSheet" with the same mobile dynamic row by clicking the cell G1 or G6 macro buttons.
https://docs.google.com/spreadsheets/d/1ISoV2q9g9L0cwP00eCfcb6k7FJ46C-E7GIOAjZCEZ3A/edit?usp=sharing
B: Hide columns and Show Columns D16
C: Hide rows and Show rows A21
For the first of your doubts, you can simply use a combinaton of getValues() and setValues() to move your data from the source to the destination creating a new row in the destination. The following piece of code has self explanatory comments and will achieve what you are aiming for (same would apply for G6):
function getDynamicRows(){
// Get source sheet
var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet 1');
// get values of the row we want to store
var range = sheet1.getRange('B4:Q4').getValues();
// Get destination sheet
var masterSheet = SpreadsheetApp.getActive().getSheetByName('MasterSheet');
// Get range of destination sheet. If we want to append a new row at the end of
// our data we get the last row and add one as that is where the new data will go
// and then set the number of columns the same as the ones from the original source
// Finally just set values to the array of values we got from the source
masterSheet.getRange(masterSheet.getLastRow()+1,1,1,range[0].length).setValues(range);
}

Find matching text in sheets

At a charity, volunteers are issued i.d. cards with QR codes. To clock in, a volunteer scans their i.d. card. A script automatically inserts the person's name into column 1 of a Google Sheet and inserts a timestamp into column 2 of the same row, to indicate timeIn. Next, we want to automate clocking out.
When a person's i.d. card is scanned, I know how to insert the person's name into a temporary holding cell. Next, I need code to check whether that person has already signed in (i.e., compare contents of the holding cell to each cell in column 1 until a match or an empty cell is found). If a match is found, then a timestamp should be entered in column 3, in the row where the person signed in, to indicate timeOut. Then, data in the temporary holding cell should be cleared.
I am very new to scripts for google apps, and have not yet figured out how to compare the values in two cells or to code a loop.
You can do the following:
Retrieve all contents of column 1 with getRange() and getValues() and push them into an array
Verify with indexOf() either the value in the temporary holding cell matches an entry of the array and if so - retrieve the entry position index
Use setValue() to insert a timestamp into a cell of column 3, row index
Here is a sample:
function myFunction() {
var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var startRow=2;
var lastRow=sheet.getLastRow();
var numberRows=lastRow-startRow+1
var Ids=sheet.getRange(startRow,1,numberRows,1).getValues();
var temporary=sheet.getRange(2,4).getValue();//please modify according to the position of your temporary cell
var array=[];
var timestamp=Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
for(var i=0;i<numberRows;i++){
array.push(Ids[i][0]);
}
var index=array.indexOf(temporary);
if(index!=-1){
sheet.getRange(index+startRow,3).setValue(timestamp);
}
}
You might want to incorporate in a doGet() function of a Web App deployment that will run the code automatically when new data is inserted into the temporary cell.

Ensure column range expands to include newly inserted rows

I have a spreadsheet with 3 charts placed on it, vertically.
Each has a header (Row 1, the header for Chart 1, is frozen).
Chart 1 data is currently within the range A2 through P26.
Data from Chart 1 is summed and referenced in the bottom row of Chart 1 (A27 through P27), as well as in cells of Chart 2 and Chart 3.
I have been working on a script that, once assigned to a button, will insert a new Row 2 at the top of the sheet (beneath Row 1, since header Row 1 is frozen).
The newly inserted row maintains conditional formatting from the below Chart 1 rows, as well as 3 formulas that are needed, but its data is not included within any of the summations elsewhere on the sheet.
Is there a way to make sure that the formulas referencing A2 through P26 always include the newly inserted Row 2 each time a new Row 2 is inserted?
Here is my code:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menu = [{name: 'Insert Row', functionName: 'insertRow'}];
ss.addMenu('Insert', menu);
}
function insertRow() {
var spsh = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spsh.getSheetByName('testSheet');
sheet.activate();
sheet.setFrozenRows(1);
sheet.insertRows(2);
var range = sheet.getRange('G2');
range.setFormula('=sum(E2:F2)');
var range = sheet.getRange("O2");
range.setFormula('=iF(K2="ordered", G2, "$0.00")');
var range = sheet.getRange("P2");
range.setFormula('=iF(K2="lost", G2, "$0.00")');
}
A cell reference that does not change with row insertion/deletion can be created with indirect(string):
=sum(indirect("A2"):A26)
This means the range will always begin with the cell A2, no matter what insertions happen.
Another approach
For completeness, I'll point out another way to deal with this: include row 1 in the range, so that insertion happens within the range. Depending on what the formulas are, they may already ignore the text content of the header row. If they don't, you can explicitly exclude the first row like this:
=sum(filter(A1:A26, row(A2:A26)>1))

Google app script to copy column values to a different sheet

I am trying to write a google app script so I can copy a few columns (C and D) from my main report sheet to a different sheet, based on the value of column M if that's equal to 0.
As shown in the pic below:
So I want to copy the "Name" and "Variety" columns into another sheet where the "Germination %" column is 0.
It can be a time based trigger, that runs after every 2 hours or onEdit also. I was trying to make it a script using OnEdit, as shown below:
function onEdit( e ){
var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("germination");
var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("watering");
var data = sheetFrom.getDataRange().getValues();
var target = new Array();// this is a new array to collect data
for(n=0;n<data.length;++n){ // iterate in the array, row by row
if (data[n][12]=="0"){ // if condition is true copy the whole row to target
target.push(data[n]);// copy the whole row
}//if
}//for
//Paste to another sheet from first cell onwards
sheetTo.getRange(1,1,target.length,2).setValues(target);
}
But I am getting errors on this "Incorrect range width, was 15 but should be 2 (line 25, file "Code")"
Line 25 is "sheetTo.getRange(1,1,target.length,2).setValues(target)"
Thanks in advance.
In the getRange(1,1,target.length,2) method you're specifying it to select only 2 columns, change it to getRange(1,1,target.length,target[0].length) to select the array length of columns.
Update:
To write only the C and D, change the target push() to:
target.push( [[data[n][2], data[n][3]] )