Is it possible for my Google sheet to automatically append a new formatted row to the end of a column when it fills up?
I would like to avoid having to manually create, say, 1000 pre-formatted empty rows in my sheet.
This is possible using Google Apps Script onEdit() trigger.
Try:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getLastRow(), 3); //Range is set from COL A - COL C up to last row with data
var lastRow = sheet.getLastRow();
var val = range.getValues();
var lastVal = val[val.length - 1];
//Check if the edit happened within Columns A-C
var range = e.range
var col = range.getColumn();
//Set sheetname and cell range where the options are coming from
var options = ss.getSheetByName("Names").getRange("A2:A")
var dropdownCell1 = sheet.getRange(lastRow + 1, 1);
var dropdownCell2 = sheet.getRange(lastRow + 1, 2);
if (col>= 1 && col <= 3 && !lastVal.includes('')) { //checks if the last row of data is filled
//Sets the data validation rule to the cells
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(options)
dropdownCell1.setDataValidation(rule)
dropdownCell2.setDataValidation(rule)
}
}
Result:
Explanation:
This uses onEdit() trigger which runs every time you make edit to a cell value. This then checks if the edit happens within Columns A-C and checks if the last row from Columns A-C are filled. It then adds the data validation rule to the cells. The dropdown comes from a sheet called 'Names' and the options are listed there.
I just did not add a code to reverse it if a data is deleted. You may edit the range if you are using different columns. Hope this helps!
Format the sheet down to the last row, as tested here in this GIF using Sequence(20), Sequence(2000).
Related
Suppose I have a Google Sheet where columns A:G are dropdown lists.
I would like to add an option to lock choices in columns A:G using a checkbox in column H, where checking the box in this column will lock columns A:G so they can not be edited (unless the checkbox in column H is de-selected).
Is it possible to do this on Google Sheets?
I have created the following script that is based on a previous script I found in a response here in StackOverflow a long time ago.
function onEdit(e)
{
var editRange = {
top : 1,
bottom : 1000,
left : 2,
right : 2
};
var cell = e.range;
// Exit if we're out of range
var thisRow = cell.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;
var thisCol = cell.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;
var val1 = e.range.getRow();
var val2 = e.range.getColumn();
var validation = SpreadsheetApp.getActive().getSheetByName("Testing Sheet").getRange(val1, val2-1);
if(cell.isChecked()){
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['Red', 'Blue']).build();
}
else{
var rule = SpreadsheetApp.newDataValidation().requireValueInList(['Black', 'White']).build();
}
validation.setDataValidation(rule);
}
I modified the range at the beginning so it only recognizes the change in column B, but you can just change it to 8 for column H. Since the script uses an onChange trigger, what you need to validate first is if the edit was made in the range where the checkboxes are, then I set the range of the cell that I was going to change based on the value from the checkbox and created the data validation rule with the expected values depending on the conditional.
In your case you can just add the rest of the ranges for the other columns with more validation variables and change the column parameter to -2, -3, or -4 depending on the cells you will be editing for example, and then create more validation rules according to the data you need in the dropdowns.
Here is an example of how this would work:
References:
onEdit()
Data Validation
first time posting and new at all of this, so I apologize in advance.
I have 2 sheets, "Origin" sheet and "Destination" sheet.
In the Origin sheet, if "APPROVED" is typed and entered in column C, then I would like:
the text in the cells from column A of that row to go to the first blank row of column C in Destination sheet AND
-for the text in the cells from column B of that row to go to the first blank row of column B in Destination sheet.
I have only been able to find the code below that works to copy the entire row. I would like to retain all of the function of deleting the row in the Origin sheet once it is copied.
Thanks in advance!
[Code
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Origin'); //source sheet
var testrange = sheet.getRange('C:C');
var testvalue = (testrange.getValues());
var csh = ss.getSheetByName('Destination'); //destination sheet
var data = [];
var j =[];
//Condition check in G:G; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'APPROVED') {
data.push.apply(data,sheet.getRange(i+1,1,1,11).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
//Delete matched rows in source sheet
for (i=0;i<j.length;i++){
var k = j[i]+1;
sheet.deleteRow(k);
//Alter j to account for deleted rows
if (!(i == j.length-1)) {
j[i+1] = j[i+1]-i-1;
}
}
}
I have two sheets. On one sheet (Sheet1), I have a column 'A' which has 5 fixed values, and a column 'B' which records the timestamp value in 'A' change. The other sheet (Sheet2) is meant to record all the changes in the first sheet in one day.
I use this simple query in the recording sheet:
=QUERY(Sheet1!A$1:X,"select * where C>="& Sheet2!D1)
with Sheet1!C has timestamps and Sheet2!D1 is the timestamp of 12:00 AM today
The problem is when I change the value of a row in C columns more than one time, instead of creating a new row in Sheet2 it change the value of that row in Sheet2 into new values.
So how do I change my code to get my desire results?
EDIT 2: here is my new code, but it doesn't help.
function importdata(x) {
// var row = x.range.getRow();
// var col = x.range.getColumn();
var addedsheet=SpreadsheetApp.getActive().getSheetByName("Change"); // Sheet where I want to keep the record of the change
var original_sheet = SpreadsheetApp.getActive().getSheetByName("Master"); //sheet where the change is happended
var compared_value = addedsheet.getRange(1,4).getValue(); // Cell D1 of sheet "Change", which has timestamp of today
var insert_area = original_sheet.getRange("A2:X").getValues() // area to get value from "Master" sheet to put into "Change"
var compared_area = original_sheet.getRange("C2:C").getValues(); // area where has timestamp
if (compared_area >= compared_value){
addedsheet.values.append([insert_area])}
} //if timestamp of one row from Master is greater than the value at Change!D1 =>append that row at the end (this is what I'm trying to do)
EDIT 3: I fixed the above code by append[insert_area][0] instead of [insert_area]
But then I have a new problem: there will a chance that a row in sheet 1 will be overwrited in sheet 2. I try something like this, but it returns nothing on the sheet.
function for_each_row(){
var addedsheet=SpreadsheetApp.getActive().getSheetByName("Change"); // Sheet where I want to keep the record of the change
var original_sheet = SpreadsheetApp.getActive().getSheetByName("Master"); //sheet where the change is happended
var compared_value = addedsheet.getRange(1,4).getValue(); // Cell D1 of sheet "Change", which has timestamp of today
var number_of_row_2 = addedsheet.getLastRow;
var number_of_row_1 = original_sheet.getLastRow();
for (var i=2; i<number_of_row_1 +1; i++){
var compared_stamp = original_sheet.getRange("C"+i).getValues();
var insert_values = (original_sheet.getRange(i,1,1,24).getValues())
if (compared_stamp > compared_value){
var insert_values = (original_sheet.getRange(i,1,1,24).getValues());
for (var j = 2; j<number_of_row_2 +1; j++){
var value_from_sheet = addedsheet.getRange(j,1,1,24).getValues();
if (insert_values ===value_from_sheet){
return
}
else(
addedsheet.appendRow(insert_values[0]))
}
}
}
}
My thought is if a row satisfies the 1st condition then the value will be check in sheet 2. If sheet 2 didn't have that row then append that row.
Issue:
If I understand you correctly, you want to do the following:
If sheet Master is edited, iterate through all rows in this sheet (excluding headers), and for each row, check the following:
Column C has a higher value than cell D1 in sheet Change.
This row, with these exact values, does not exist in Change.
If these conditions are meet, append the row to Change.
Solution:
Use filter and some to filter out rows that don't match your two conditions, and use setValues to write the resulting rows to your other sheet.
Code snippet:
function onEdit(e) {
var editedSheet = e ? e.range.getSheet() : SpreadsheetApp.getActiveSheet();
if (editedSheet.getName() === "Master") {
var addedSheet = SpreadsheetApp.getActive().getSheetByName("Change");
var compared_value = addedSheet.getRange(1,4).getValue();
var newData = editedSheet.getRange("A2:X" + editedSheet.getLastRow()).getValues();
var currentData = addedSheet.getRange("A2:X" + addedSheet.getLastRow()).getValues();
var filteredData = newData.filter(row => row[2] >= compared_value)
.filter(row => !currentData.some(currentRow => JSON.stringify(currentRow) === JSON.stringify(row)));
addedSheet.getRange(addedSheet.getLastRow()+1,1,filteredData.length,filteredData[0].length).setValues(filteredData);
}
}
Note:
An easy way to check if two rows have the same values is using JSON.stringify(row).
I'm assuming the timestamps are not Dates. If they are, you should compare them using getTime(). So you should change the corresponding code to newData.filter(row => row[2].getTime() >= compared_value.getTime()).
I have a sheet with is collecting form responses. I'm then using the QUERY function to pull all the data into a separate sheet to action using the following formula:
=QUERY(formsubmissions,"SELECT *")
where formsubmissions in the Named Range.
Once four steps have taken place the user then selects Completed = Ýes' which triggers the following script:
function onEdit() {
var sheetNameToWatch = "R+R;
var columnNumberToWatch = 15;
var valueToWatch = "Yes";
var sheetNameToMoveTheRowTo = "Completed";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() == columnNumberToWatch && range.getValue() == valueToWatch) {
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
sheet.deleteRow(range.getRow());
}
}
This script executes and functions correctly, moving the row into the Çompleted sheet and deleting from the active sheet. However, the row is only momentarily deleted and appears back almost instantaneously. I guess this is because it still matches the QUERY parameters so it is pulled in again straight away.
How can I ensure it stays deleted either by modifying the query or by modifying the script?
As you've surmised, this occurs because the row in the original responses sheet still fulfils the query criteria. You could modify your query to exclude any unique identifiers by checking that it doesn't already appear in the Completed sheet - Say that column A is a reference number or timestamp, you could try the following:
=QUERY(formsubmissions,"SELECT * where A <> "&Completed!A:A)
This then checks the array in Completed A:A for the same value, and excludes it from the query result if present.
First of all I must say that my level of knowledge of Google App Scripts is almost nil. I tried to create a script using the macro utility, but the resulting code is too long. I will be very grateful if someone can help me simplify this code. I indicate below the parameters of the subject:
I have approximately 50 tabs (sheets) in a spreadsheet, although they can be more. (For short, the spreadsheet that is attached as an example has 5 tabs, whose content, also for short, is the same.)
Each tab contains data in cells B8:L17 (11 columns and 10 rows of data).
On a tab called "Index" are the names of the 50 tabs. The names of the tabs must begin in B2. Between one tab name and the next there are 9 empty rows. (All the above I have been able to solve.)
What I want to do --using the "Indirect" formula- is the following:
- That the data of sheet 1 be copied in Index in C2: M11.
- That the data on sheet 2 be copied to Index at C12: M21.
- That the data on sheet 3 be copied to Index in C22: M31.
- That the data of sheet 4 be copied in Index in C32: M41.
- That the data of sheet 5 be copied in Index in C42: M51.
--Etc.
Thank you for your attention.
function INDIRECT() {
var s = SpreadsheetApp.getActive();
s.getRange("c2").setFormula('=INDIRECT("\'"&Index!b2&"\'!b8:l17")');
s.getRange("c2").offset(10, 0).activate();
s.getCurrentCell().offset(-10, 0).copyTo(s.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
s.getCurrentCell().offset(10, 0).activate();
s.getCurrentCell().offset(-20, 0).copyTo(s.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
s.getCurrentCell().offset(10, 0).activate();
s.getCurrentCell().offset(-30, 0).copyTo(s.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
s.getCurrentCell().offset(10, 0).activate();
s.getCurrentCell().offset(-40, 0).copyTo(s.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
The OP needs to populate a master sheet with the contents of other sheets.
The following code assumes that the names of the sheets are already populated in Column B (as per the OP spreadsheet).
The equivalent query formula (in Cell C3, for example) looks like this:
=query(Funda!$B$8:$L$17;" Select * ").
This code does not produce a custom formula. It is a routine that might be run only once, looping through Column B of the Master sheet, and inserting the appropriate query into Column C, based on the sheet names listed in Column B. The code might be run only once. Unless there is a change in the spreadsheet layout, or more sheets are added, the query formulas inserted by the code will update the master sheet for all changes on sub-sheets.
function so54463600() {
// setup spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mastername = "Master"; // Change this sheet name to whatever you want
var sheet = ss.getSheetByName(mastername);
// The sheet data range
var datarange = "$B$8:$L$17";
// set the data and number of sheets in Column B
var Bvals = sheet.getRange("B1:B").getValues();
var Blast = Bvals.filter(String).length;
var lastRow = sheet.getLastRow();
//Logger.log("DEBUG: the last row = "+lastRow);//DEBUG
// loop through the rows of column B
for (var x = 0; x < lastRow; x++) {
// action if the cell has contents
if (Bvals[x][0].length != 0) {
// Logger.log("DEBUG: x = "+x+", Value = "+Bvals[x][0]+", length: "+Bvals[x][0].length);//DEBUG
// sample query: =query(Funda!$B$8:$L$17;" Select * ")
var formula = "=query(" + Bvals[x][0] + "!" + datarange + ";" + '"' + " Select * " + '")';
// Logger.log("DEBUG: the formula is "+formula);//DEBUG
// Location to set query formula
Logger.log("target range:" + sheet.getRange(x + 1, 3).getA1Notation());
// set the formula
sheet.getRange(x + 1, 3).setFormula(formula);
}
}
}
REVISION 4 Feb 2019
Update Sheet Names Programmatically
The number of sheets in a spreadsheet can be 50 or more. Sheet names can change, sheets can be added or deleted. Therefore, in order to ensure that the data shown on the master sheet is complete and accurate, it is desirable that sheet names be inserted programmatically, rather than manually.
This revision includes a new subroutine buildsheetnames AND some changes to the original code. Regard this is a complete substitution rather than a simple add-on.
Sourcing sheet names
The sheet names are obtained first with getSheets(), and then getName().
The user organises the sheets in the screen order that suits them; only sheets listed to the right of the "Master" sheet will be included in the names displayed by the routine.
A user defined variable startingsheetNumber is included to define the first sheet to be displayed on the "Master" list. This is obtained by counting ALL the sheets from left to right, beginning the count at zero. The count value of the first sheet to the right of "Master" should be assigned to this variable. The rest of the sheets to the right of "Master" will be automatically included.
function so54463600mk2() {
// setup spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mastername = "Master";
var sheet = ss.getSheetByName(mastername);
// The sheet data range
var datarange = "$B$8:$L$17";
// select the existing sheet data and clear the contents
// do this in case a sheet is added or deleted; minimize chance of not detecting an error.
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
//Logger.log("last row = "+lastRow+", last Column: "+lastColumn);
var masterrange = sheet.getRange(2, 2, lastRow - 1, lastColumn - 1);
masterrange.clear();
// update the sheet names in column B
// run the sub-routine buildsheetnames
buildsheetnames(mastername);
// set the data and number of sheets in Column B
var Bvals = sheet.getRange("B1:B").getValues();
var Blast = Bvals.filter(String).length;
var lastRow = sheet.getLastRow();
//Logger.log("DEBUG: the last row = "+lastRow);//DEBUG
// loop through the rows of column B
for (var x = 0; x < lastRow; x++) {
// action if the cell has contents
if (Bvals[x][0].length != 0) {
// Logger.log("DEBUG: x = "+x+", Value = "+Bvals[x][0]+", length: "+Bvals[x][0].length);//DEBUG
// sample query: =query(Funda!$B$8:$L$17;" Select * ")
//var formula = "=query(" + Bvals[x][0] + "!"+datarange+";"+'"'+" Select * "+'")';
var formula = "=query(" + "'" + Bvals[x][0] + "'!" + datarange + ";" + '"' + " Select * " + '")';
// Logger.log("DEBUG: the formula is "+formula);//DEBUG
// Location to set query formula
Logger.log("target range:" + sheet.getRange(x + 1, 3).getA1Notation());
// set the formula
sheet.getRange(x + 1, 3).setFormula(formula);
}
}
}
function buildsheetnames(mastername) {
// setup spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(mastername);
// move the curcor to cell B2
var row = 2;
var column = 2;
sheet.getRange(2, 2).activate();
// get the list of sheets
var sheetlist = ss.getSheets();
// Logger.log("DEBUG: Number of sheets: "+sheetlist.length);//DEBUG
// Displaying Sheet names on the master sheet
// Instructions:
// 1 - View the spreadsheet with sheets laid out at the bottom of the screen
// 2 - Move the sheets into the order that you want;
// 2a - Sheets to the left of "Master" (or whatever sheet you define as "mastername") wouldn't be included in the sheet names written onto Master
// 2b - Only the names of those sheets to the right of "Master" will be displayed.
// 3 - Count ALL the sheets, from left to right of screen. The first sheet will be zero, the second sheet will be one, and so on.
// 4 - Stop when you reach the first sheet that you want the name displayed on Master
// 5 - Update the count value for that sheet to the variable 'startingsheetNumber'.
// 6 - Note: the variable "sheetrowseparation" is the number of rows between each name;
// 6a - This is the same as the number of data rows on each data sheet.
// 6b - If the number of data rows ever changes, then you can change this variable.
var startingsheetNumber = 6;
var sheetrowseparation = 10;
// loop through the sheets
if (sheetlist.length > 1) {
for (var i = startingsheetNumber; i < sheetlist.length; i++) {
//Logger.log("DEBUG: Sheet#: "+i+", Sheet name: "+sheetlist[i].getName());//DEBUG
sheet.getRange(row, column).setValue(sheetlist[i].getName());
row = row + sheetrowseparation;
}
}
return;
}