getSheetByName seems to get ANY active sheet - google-apps-script

I would like for the following function to only run on my "Estimate" tab, but it runs on all tabs. I thought calling the sheet by name would resolve this, but it doesn't. I'm very new to GAS and have minimal coding experience, so I'm obviously just doing something wrong.
Here is a link to my sheet
function onEdit(){
//https://www.youtube.com/watch?v=8aOn0VMgG1w
//var ss = SpreadsheetApp.getActiveSpreadsheet();
//var estss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Estimate');
//commented out to try the var below...
//same result
var estss = SpreadsheetApp.getActive().getSheetByName('Estimate');
//var catss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Categories');
//commented out to try the var below...
//same result
var catss = SpreadsheetApp.getActive().getSheetByName('Categories');
var activeCell = estss.getActiveCell();
if(activeCell.getColumn() == 1 && activeCell.getRow() > 1){
activeCell.offset(0, 1).clearContent().clearDataValidations();
var cat = catss.getRange(1,2,1,catss.getLastColumn()).getValues();
var catIndex = cat[0].indexOf(activeCell.getValue()) + 2;
if(catIndex != 0){
var validationRange = catss.getRange(2, catIndex,catss.getLastRow());
var validationRule = SpreadsheetApp.newDataValidation().requireValueInRange(validationRange).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}
}
When selecting a category in column A on the "Estimate" tab, the following column (B) should set a data validation with all of the sub-categories (rows below the corresponding category), from the "Categories" tab. It basically works, but it also works on every other tab. I would like for it to work on the "Estimate" tab only.

Instead of the active methods, use the Event object
If your event object is e -> function onEdit(e){}
e.range returns the edited range, then you could use
e.range.getSheet().getName() to get the name of the active sheet
then you could use an if statement like
if(e.range.getSheet().getName() !== 'Sheet 1') return;
to stop the execution of the script when the active sheet's name isn't Sheet 1

Related

Script is triggering but nothing happens?

I want to create a script that moves data from one sheet to another when I mark it as completed in a particular column. Using some other code I found on the internet, I have this, but when I go in and change that status to completed nothing happens. The trigger page in google apps script says it's executing, but it isn't doing anything to the actual sheet. Here is the code:
function onEdit(e) {
if(SpreadsheetApp.getActiveSpreadsheet() == "Planner" && e.value == "Completed"){ //If the edit was on Planner marking the Status "Completed"
var spr = SpreadsheetApp.getActiveSpreadsheet();
var myRange = e.range.offset(0,-3,0,3).getValue() //get the information from Planner
//find the first row of Calendar where completed assignments is blank
var column = spr.getRange('O:O');
var values = column.getValues(); // get all data in one call
var ct = 0;
while ( values[ct][0] != "" ) {
ct++;
ct++;
e.source.getSheetByName("Calendar").getRange(ct,15,1,3).setValues(myRange).getValues(); //copy the values from Planner to Calendar
e.source.getSheetByName("Planner").getRange(myRange).setValues("").getValues(); //delete values from Planner
;}
return (ct);
}
}
I assume something is wrong with it but I don't know what. I've never used apps script before so I honestly don't know what I'm doing. Here is the sheet:
Sheet
I want to move completed homework from the planner sheet to the calendar sheet when I change the status. Thanks so much for any help!!
EDIT:
I used lamblichus's code and it works great except that I still want to delete the data from the Planner Sheet after I move it. I tried this code and it didn't work:
function onEdit(e) {
const ss = e.source;
const range = e.range;
const sheet = range.getSheet();
if (sheet.getName() == "Planner" && e.value == "Completed") {
var otherData = range.offset(0,-3,1,3).getValues();
var currentClass = range.offset(0,-4).getMergedRanges()[0].getValue();
var [task,,date] = otherData[0];
var targetSheet = ss.getSheetByName("Calendar");
var targetRange = targetSheet.getRange("O1").getNextDataCell(SpreadsheetApp.Direction.DOWN).offset(1,0,1,3);
targetRange.setValues([[date,task,currentClass]]);
var initialSheet = ss.getSheetByName("Planner");
var initialRange = initialSheet.range.offset(0,-3,1,3);
initialRange.clearContent(); //delete values from Planner
}
}
Issues and solution:
There are several issues with your current code:
If you want to check the sheet name, you have to use Sheet.getName(). SpreadsheetApp.getActiveSpreadsheet() just returns the active spreadsheet, not sheet, and not its name anyway.
If you want to get values from multiple cells, you should use getValues(), not getValue().
The third parameter of offset corresponds to the number of rows of the resulting range. Therefore, it should not be 0.
The "Class" name is in a merged range, and only the top-left cell in a merged range includes the corresponding value. To get that value, you can use getMergedRanges and retrieve the first element in the resulting array. Since getValue() returns the value in the top-left cell of a range, it will return the "Class" name.
Code sample:
function onEdit(e) {
const ss = e.source;
const range = e.range;
const sheet = range.getSheet();
if (sheet.getName() == "Planner" && e.value == "Completed") {
var otherDataRange = range.offset(0,-3,1,3);
var otherData = otherDataRange.getValues();
var currentClass = range.offset(0,-4).getMergedRanges()[0].getValue();
var [task,,date] = otherData[0];
var targetSheet = ss.getSheetByName("Calendar");
var targetRange = targetSheet.getRange("O1").getNextDataCell(SpreadsheetApp.Direction.DOWN).offset(1,0,1,3);
targetRange.setValues([[date,task,currentClass]]);
otherDataRange.clearContent();
}
}
It looks like a syntax error on line 14, you put ;}, it should be }; you don't need to tell JavaScript (the coding language that AppScript is based on) when you end comments. But it likes it when you tell it when you end while loops.
Here is the updated code.
function onEdit(e) {
if(SpreadsheetApp.getActiveSpreadsheet() == "Planner" && e.value == "Completed"){ //If the edit was on Planner marking the Status "Completed"
var spr = SpreadsheetApp.getActiveSpreadsheet();
var myRange = e.range.offset(0,-3,0,3).getValue() //get the information from Planner
//find the first row of Calendar where completed assignments is blank
var column = spr.getRange('O:O');
var values = column.getValues(); // get all data in one call
var ct = 0;
while ( values[ct][0] != "" ) {
ct++;
ct++;
e.source.getSheetByName("Calendar").getRange(ct,15,1,3).setValues(myRange).getValues(); //copy the values from Planner to Calendar
e.source.getSheetByName("Planner").getRange(myRange).setValues("").getValues(); //delete values from Planner
};
return (ct);
};
}

Why is this function running, if I'm on a different tab (Sheets)

The code below seems to run, even though I'm on a different page and have set that as a condition:
function setItemListProductPg(){
var tabLists = "ArquivoItens";
var tabValidation = "Painel do Produto";
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabValidation);
var arquivoItens = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabLists);
var activeCell = ss.getActiveCell();
var itemList = arquivoItens.getRange('B2:B');
if(ss.getSheetName() === "Painel do Produto" && activeCell.getColumn() == 3 && activeCell.getRow() == 3){
var arrayValues = itemList.getValues();
// define the dropdown/validation rules
var rangeRule = SpreadsheetApp.newDataValidation().requireValueInList(arrayValues);
// set the dropdown validation for the row
activeCell.setDataValidation(rangeRule); // set range to your range
}
}
Could you let me know where this is failing?
Thank you!
I think this is what you want:
function setItemListProductPg(e){
var sh=e.range.getSheet();
if(sh.getName()=="ArquivoItens" && e.range.columnStart==3 && e.value==3){
var rangeRule= e.source.newDataValidation().requireValueInList(sh.getRange(2,2,sh.getLastRow()-1,1).getValues().map(function(r){return r[0];}));
e.range.setDataValidation(rangeRule);
}
}
And of course you will need to set the installable trigger manually via edit/Get Current Project Triggers.
Because you are not querying for the active tab, only for the active spreadsheet
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(tabValidation); will always retrieve the sheet with the name as specified in tabValidation, no matter if it is the active sheet or not.
Instead, you need to define:
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
if(ss.getSheetName() === "Painel do Produto"...){
...

How to refresh a filter onEdit() in Google sheets?

I have a sheet where I fill data with Hlookups depending on the values I choose in dropdowns.
I want to filter (hide) the rows that have a NULL or blank value in column 3 each time I change the values in the dropdowns (which changes the whole dataset).
If I create a normal filter, it doesn't refresh when the data changes.
var PARAMETER_ROW_NUMBER = 5; //The parameters goes from Row 1 to this Row
var PARAMETER_COLUMN_NUMBER = 2; //The column where the dropdowns with the parameters for the VLOOKUPs are
function onEdit()
{
var thisSheet = SpreadsheetApp.getActiveSheet();
if( thisSheet.getName() == "By Place" )
{
var cell = thisSheet.getActiveCell();
var cellRow = cell.getRow();
var cellColumn = cell.getColumn();
if( cellColumn == PARAMETER_COLUMN_NUMBER && cellRow <= PARAMETER_ROW_NUMBER)
{
setFilter(); // Execute the filter to clean null rows each time I change the values in the dropdowns
var rowDiff = PARAMETER_ROW_NUMBER - cellRow;
cell.offset( 1, 0, rowDiff).setValue(''); // As the parameters are dependent dropdowns, I clear the dropdowns if one changes
}
}
}
function setFilter()
{
var ss = SpreadsheetApp.getActiveSheet();
var rang = ss.getDataRange();
var filtercriteria = SpreadsheetApp.newFilterCriteria().setHiddenValues([' ','']).build();
var filter = rang.getFilter() || rang.createFilter();
filter.setColumnFilterCriteria(3, filtercriteria); // I want to hide the rows which has a null or blank in column 3
}
The setFilter() function doesn't work.
The array you're using to set the hidden values is not correct, try your code like this:
function setFilter()
{
var ss = SpreadsheetApp.getActiveSheet();
var rang = ss.getDataRange();
var filterCriteria = SpreadsheetApp
.newFilterCriteria()
.setHiddenValues(['NULL', ''])
.build();
var filter = rang.getFilter() || rang.createFilter();
filter.setColumnFilterCriteria(3, filterCriteria);
}
Also, if you want to see the logs from your onEdit executions, you can check them on your Apps Script file by clicking in View - > Executions, there you will be able to see the errors you are getting.
Docs
I used these docs to help you:
setColumnFilterCriteria(columnPosition, filterCriteria).
Class FilterCriteriaBuilder.

How to change an onEdit function to work whenever a script runs? - Google Sheets

I have written an onEdit function, which creates a dropdown list which changes depending on the adjacent value entered into column G of the same row.
The code is:
function onEdit() {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();;
var OEsheet = ss.getSheetByName("OE names");
var SOsheet = ss.getSheetByName("Sales Order");
var activeCell = SOsheet.getActiveCell();
if(activeCell.getColumn() == 7 && activeCell.getRow() > 1 && ss.getSheetName() == "Sales Order") {
activeCell.offset(0, -6).clearContent().clearDataValidations();
var OEnames = OEsheet.getRange(1, 1, 1, OEsheet.getLastColumn()).getValues();
var OEnamesIndex = OEnames[0].indexOf(activeCell.getValue()) + 1;
if(OEnamesIndex != 0){
var validationRange = OEsheet.getRange(2, OEnamesIndex, OEsheet.getLastRow());
var validationRule = app.newDataValidation().requireValueInRange(validationRange).build();
activeCell.offset(0, -6).setDataValidation(validationRule);
}
}
}
This script works perfectly, but the problem is the data added to column G for my spreadsheet will be added by a script, not manually so I have opted to merge this function with another function so it triggers the creation of the data validation for the whole of Column A when the previous script is triggered, rather than on a manual edit. Therefore, I changed the code to this (which I will merge with a previous function):
function DropDowns() {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();;
var OEsheet = ss.getSheetByName("OE names");
var SOsheet = ss.getSheetByName("Sales Order");
var DDcolumn = SOsheet.getRange("A2:A");
var Bcolumn = SOsheet.getRange("G2:G");
Bcolumn.clearContent().clearDataValidations();
var OEnames = OEsheet.getRange(1, 1, 1, OEsheet.getLastColumn()).getValues();
var OEnamesIndex = OEnames[0].indexOf(Bcolumn.getValue()) + 1;
if(OEnamesIndex != 0){
var validationRange = OEsheet.getRange(2, OEnamesIndex, OEsheet.getLastRow());
var validationRule = app.newDataValidation().requireValueInRange(validationRange).build();
DDcolumn.setDataValidation(validationRule);
}
}
However, this does not work properly - it creates a data validation for the whole column (which is what I wanted), but it does not use the value in the adjacent column of the same row to create this data validation (because I had to remove the activeCell functionality as the data will not be manually entered I think). It now seems to be using only Column A in the OE names sheet to create the data validation for the row, rather than the column in the OE sheet which corresponds to the value in column G of the Sales Orders sheet.
This is a link to a copy of my spreadsheet with all the irrelevant scripts and data removed: https://docs.google.com/spreadsheets/d/1bligSkSDr0dtU3Zwj1c-SasvKbHqX-QhbM8zysIvM-Q/edit?usp=sharing
How can I fix this so that the script runs and adds dropdown lists to the whole column, but the content of these lists still change depending on the adjacent value in column G?
Thank you

function onEdit() runs only partially

I have a very frustrating problem on my hands and I turn to you for help once more. I had the onEdit() function below which, together with the auxiliary functions, worked fine.
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var activeCell = activeSheet.getActiveCell();
//Check if the sheet is a JOb sheet and the cell us the status cell
if ( activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 4 && activeCell.getColumn() == 15 ) {
var targetSheet = ss.getSheetByName('Active Jobs');
var jobRowNumber = findJobIdRow();
var sourceCell = activeSheet.getRange(4,15);
sourceCell.copyTo(targetSheet.getRange(jobRowNumber,16));
}
if (activeSheet.getName().indexOf("Job ID") != -1 && activeCell.getRow() == 2 && activeCell.getColumn() == 15){
var switchValue = activeCell.getValue();
switch (switchValue){
case "On hold (i)":
case "On hold (ii)":
case "On hold (iii)":
case "To be assigned":
//Write date to active jobs sheet
addDateToActive("TBC");
break;
case "In progress":
var newDate = Browser.inputBox("Please enter report out date, example 18-Aug-2017");
addDateToActive(newDate);
break;
//default:
//Browser.msgBox("GOTHERE");
}
}
}
function findJobIdRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var jobID = ss.getActiveSheet().getRange(2,1).getValue();
var column = ss.getSheetByName('Active Jobs').getRange(2,1,ss.getSheetByName('Active Jobs').getMaxRows()-2,1);
var values = column.getValues(); // get all data in one call
for(var ct = 0; ct < values.length-1; ct++){
if(values[ct][0] == jobID){
var ct = ct+2;
break;
}
}
return ct;
}
function addDateToActive(input){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var activeCell = activeSheet.getActiveCell();
var jobid = activeSheet.getRange(2,1).getValue().toString();
var activeJobSheet = ss.getSheetByName("Active Jobs");
var activeJobs = activeJobSheet.getRange(1,1,activeJobSheet.getLastRow(),1).getValues();
activeJobs = ColumnToArray(activeJobs);
var jobrow = activeJobs.indexOf(jobid)+1;
if (jobrow == -1){
Browser.msgBox("Job Id not preent on Active Jobs sheet");
}else{
activeJobSheet.getRange(jobrow,15).setValue(input);
}
}
Then I included some code in this script which was supposed to send out some e-mails to people if some dates were approaching today's date. There were some problems with that code because of authorization requirement so I moved it into it's own separate function and came back to the original script that is posted above. Now the problem I am facing is, although this script works fine if ran from the script editor, manually run from a drawing button in the spreadsheet, or is ran by a on edit trigger I set up from the "Current project triggers" menu, it will not do the entire script if the script is triggered by the onEdit() function name. It does the first bit where it copies the content of a cell across but not the second bit with the case switch.
The obvious fix would be to just set up the trigger from the "Current project triggers" but this onEdit detection needs to apply to anyone in my team that edits this sheet. If I set it up like that it will work for me but no one else from my team.
Any help would be appreciated.
Setting up the trigger via the function name onEdit() proving tricky I wrote this bit of code and attached it to a drawing in the sheet. Then instructed all the users to click it which set up the trigger for them. This solved the problem and the trigger works fine now.
function triggerSetUp(){
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("enforcer").forSpreadsheet(sheet).onEdit().create();
}