Auto Sort not working on Multiple Sheets within one Google Sheet - sorting

I want Sheet 2 (Titled "Deals in Escrow") to auto sort by date and Sheet 1 (Titled "Loan Inquiries") to auto sort by last name. Both Sheets are within a single Google Sheet. I have found the following script, and I modified it slightly and it works great on Sheet 2 to auto sort by date;
//Updates sort for range automatically
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 7;
var tableRange = "A3:T99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}
However, I want the 1st Sheet to auto sort by Last Name which is in Column 2, rather than Column 7 that the script refers to.
For what it's worth, I made the following changes to the script and added in the following script which works well to sort by last name in column 2 on Sheet 1;
//Updates sort for range automatically
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 2;
var tableRange = "A3:T99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}
But the problem is that by doing so, the other script to auto sort by date in Sheet 2 has now been disabled.
I've also tried creating a Name Range in each sheet and putting NamedRange1 and NameRange2 in the table range section of the script. It hasn't changed anything. Sheet 1 is still sorting by last name and Sheet 2 is not sorting.
//Updates sort for range automatically
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 2;
var tableRange = "NamedRange1"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}

Try:
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet().getName()
var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Loan Inquiries"){
var columnToSortBy = 2;
var tableRange = "A3:T99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}}
else if(sheet=="Deals in Escrow"){
var columnToSortBy = 7;
var tableRange = "A3:T99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
else{return}
}}
Test spreadsheet:
https://docs.google.com/spreadsheets/d/13vveA0n4w84yQ71no7LgGonz_wLE7H_RA1ocDOtLZPQ/edit?usp=sharing

I would recommend using the getSheetByName method instead :
for example:
var ss = SpreadsheetApp.getActiveSheet().getSheetByName('Deals in Escrow');

Related

How to make this script run in all tabs except certain tabs (Sheets)?

I'm a total newbie when it comes to scripts and I honestly don't really use it often at all but I thought it'd be fun to automatize an alphabetical order sorting I wanted to do and so I used this script:
/** Build a menu item
From https://developers.google.com/apps-script/guides/menus#menus_for_add-ons_in_google_docs_or_sheets
**/
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createMenu('Sort');
if (e && e.authMode == ScriptApp.AuthMode.NONE) {
// Add a normal menu item (works in all authorization modes).
menu.addItem('Sort Sheet', 'sort');
} else {
// Add a menu item based on properties (doesn't work in AuthMode.NONE).
var properties = PropertiesService.getDocumentProperties();
var workflowStarted = properties.getProperty('workflowStarted');
if (workflowStarted) {
menu.addItem('Sort Sheet', 'sort');
} else {
menu.addItem('Sort Sheet', 'sort');
}
menu.addToUi();
}
}
function sort() {
/** Variables for customization:
Each column to sort takes two variables:
1) the column index (i.e. column A has a colum index of 1
2) Sort Asecnding -- default is to sort ascending. Set to false to sort descending
**/
//Variable for column to sort first
var sortFirst = 3; //index of column to be sorted by; 1 = column A, 2 = column B, etc.
var sortFirstAsc = true; //Set to false to sort descending
//Variables for column to sort second
var sortSecond = 1;
var sortSecondAsc = true;
//Number of header rows
var headerRows = 1;
/** End Variables for customization**/
/** Begin sorting function **/
var activeSheet = SpreadsheetApp.getActiveSheet();
var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn());
range.sort([{column: sortFirst, ascending: sortFirstAsc}, {column: sortSecond, ascending: sortSecondAsc}]);
}
It worked very well but I wondered if there was a way to not have it work in two specific tabs of the same sheets?
I believe your goal as follows.
You want to execute the script of sort for the sheets except for the specific sheets.
In this case, how about declaring the excluded sheet names and checking the current sheet using the excluded sheet names? When this is reflected to your script, it becomes as follows.
Modified script:
In this case, please set the sheet names you want to exclude to excludeSheetNames. At sample script, when the active sheet is "Sheet1" and "Sheet2", the script below the if statement is not run.
function sort() {
var excludeSheetNames = ["Sheet1", "Sheet2"]; // <--- Added
var sortFirst = 3;
var sortFirstAsc = true;
var sortSecond = 1;
var sortSecondAsc = true;
var headerRows = 1;
var activeSheet = SpreadsheetApp.getActiveSheet();
var sheetName = activeSheet.getSheetName();
if (excludeSheetNames.includes(sheetName)) return; // <--- Added
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, sheet.getLastColumn());
range.sort([{ column: sortFirst, ascending: sortFirstAsc }, { column: sortSecond, ascending: sortSecondAsc }]);
}
For example, if you want to run the script below the if statement for only excludeSheetNames, please modify if (excludeSheetNames.includes(sheetName)) return; to if (!excludeSheetNames.includes(sheetName)) return;.
Reference:
includes()

Returning certain rows which meet a criteria - Google Apps Script

What I am trying to do is: I have a list, with N being a date and O being a checkbox. I need to get the rows which =N < Today() && O=False, then return A:B of those corresponding rows. I've tried it every which way, and I can't get it to work. Any suggestions?
function msg1(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var wscl = ss.getSheetByName('Connection List');
var contact = wscl.getRange("A2:B").getValues();
var msg1date = wscl.getRange("N2:N").getValues();
var msg1sent = wscl.getRange("O2:O").getValues();
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var now = new Date();
var yesterday = new Date(now.getTime() - MILLIS_PER_DAY);
for(var i=0;i<msg1sent.length;i++){
if(msg1sent =="FALSE"&& msg1date < yesterday){
var row=i+1;
}
}
}
If you use getValues() of a checkbox it returns true or false booleans. If you use getDisplayValues() it returns "TRUE" or "FALSE" strings. And for the dates I just used valueOf() but you can also use getTime(). The easiest way to figure all of this out is to create some intermediate temporary variables and view them in the Script Debugger and you can see all of the return values there.
function msg1(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Connection List');
var ct=sh.getRange(2,1,sh.getLastRow()-1,2).getValues();
var date=sh.getRange(2,14,sh.getLastRow()-1,1).getValues();//date
var sent=sh.getRange(2,15,sh.getLastRow()-1,1).getValues();//checkbox
var dt=new Date();
var rows=[];
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//0000 or midnight
for(var i=0;i<sent.length;i++){
var t1=sent[i][0];
var t2=new Date(date[i][0]).valueOf();
var t3=today;
if(sent[i][0]==false && new Date(date[i][0]).valueOf()<today){
rows.push(ct[i]);
}
}
Logger.log(rows);
}
If you use getDisplayValues() then it would look like this:
function msg1(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Connection List');
var ct=sh.getRange(2,1,sh.getLastRow()-1,2).getValues();
var date=sh.getRange(2,14,sh.getLastRow()-1,1).getValues();//date
var sent=sh.getRange(2,15,sh.getLastRow()-1,1).getDisplayValues();//checkbox
var dt=new Date();
var rows=[];
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
for(var i=0;i<sent.length;i++){
var t1=sent[i][0];
var t2=new Date(date[i][0]).valueOf();
var t3=today;
if(sent[i][0]=="FALSE" && new Date(date[i][0]).valueOf()<today){
rows.push(ct[i]);
}
}
Logger.log(rows);
}

Set the sourceRange of Data Validation to an array of values

I'm creating a social media outreach tracker. I want to create a drop-down list of the contact name. The problem is that I have two sources of names on two different sheets.
I wrote a script that pulls the names from the two different sources and combines them to a single array.
I was hoping to set the source range as that array.
Here is my code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var castingDirectorsTab = auditionsSheet.getSheetByName("Casting Directors");
var contactsTab = auditionsSheet.getSheetByName("Contacts");
var socialMediaOutreachTab = auditionsSheet.getSheetByName("Social Media Outreach");
var lastRowCD = castingDirectorsTab.getLastRow();
var lastRowContacts = contactsTab.getLastRow();
var activeCell = socialMediaOutreachTab.getActiveCell();
var activeColumn = activeCell.getColumn();
// get data
var castingDirectorNameData = castingDirectorsTab.getRange(2, 1, lastRowCD, 1).getValues();
var contactNameData = contactsTab.getRange(2, 1, lastRowContacts, 1).getValues();
//get name data to a single arrays
var castingDirectorName = [];
castingDirectorNameData.forEach(function(yr) {
castingDirectorName.push(yr[0]);
});
var contactName = [];
contactNameData.forEach(function(yr) {
contactName.push(yr[0]);
});
// get rid of the empty bits in the arrays
for (var x = castingDirectorName.length-1; x > 0; x--) {
if ( castingDirectorName[x][0] === undefined ) {
castingDirectorName.splice( x, 1 )
}
}
for (var x = contactName.length-1; x > 0; x--) {
if ( contactName[x][0] === undefined ) {
contactName.splice( x, 1 )
}
}
//combine two data sources for data validation
var combinedNames = [];
combinedNames.push(castingDirectorName + contactName);
Logger.log (combinedNames);
Logger.log( typeof combinedNames);
// data validation set up and build
if (activeColumn == 1 && auditionsSheet.getName() == "Social Media Outreach") {
var range = auditionsSheet.getRange(activeCell.getRow(), activeColumn +1);
var sourceRange = combinedNames;
setDataValid_(range, sourceRange)
}
}
When I enter a date in Col A on Social Media Outreach, nothing happens in Col 2.
I was using an existing working nested data validation script I have but the sourceRange pulls from a sheet based on the value in the active cell. Here is that code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
// data validation for Auditions Tab Projet Type to Project Details
if (aColumn == 9 && aSheet.getName() == 'Auditions') {
var range = aSheet.getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('RefTables!' + aCell.getValue())
setDataValid_(range, sourceRange)
}
}
For this script when I select from the data validation drop-down, a new data validation comes up in the next col with the appropriate secondary data validation.
So the question is, can the source range be set to an array or do I need to put the names back into my sheet to reference a la the second script.
I've looked through the documentation and searched and can't find an answer. I'm relatively new to GAS and am not sure of all the inner workings of the data validation builder.

Auto sorting 2 sheets based on 1 of them

I'm running a spreadsheet which contains multiple sheets, in Sheet3 I'm inputting some data and running an auto sorting code, which sorts it ascending by column D.
Sheet3 Example | Sheet1 Example
The "name" and "location" in Sheet1 are imported from Sheet3 so they swap position when Sheet3 does the sorting, however, the problem is that the info from D to F (Sheet1) isn't swapping and it will display for wrong people.
This is the script I'm using:
Modified it slightly to work for a specific sheet, since I didn't need to auto sort the whole document at the time.
/*
* #author Mike Branski (#mikebranski)
* #link https://gist.github.com/mikebranski/285b60aa5ec3da8638e5
*/
var SORT_COLUMN_INDEX = 4;
var ASCENDING = true;
var NUMBER_OF_HEADER_ROWS = 2;
var SHEET_NAME = 'Sheet3';
var activeSheet;
function autoSort(sheet) {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == SHEET_NAME) {
var range = sheet.getDataRange();
if (NUMBER_OF_HEADER_ROWS > 0) {
range = range.offset(NUMBER_OF_HEADER_ROWS, 0, (range.getNumRows() - NUMBER_OF_HEADER_ROWS));
}
range.sort( {
column: SORT_COLUMN_INDEX,
ascending: ASCENDING
} );
}
}
function onEdit(event) {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == SHEET_NAME) {
var editedCell;
activeSheet = SpreadsheetApp.getActiveSheet();
editedCell = activeSheet.getActiveCell();
if (editedCell.getColumn() == SORT_COLUMN_INDEX) {
autoSort(activeSheet);
}
}
}
function onOpen(event) {
var s = SpreadsheetApp.getActiveSheet();
if (s.getName() == SHEET_NAME) {
activeSheet = SpreadsheetApp.getActiveSheet();
autoSort(activeSheet);
}
}
function onInstall(event) {
onOpen(event);
}
So basically when I edit Sheet3 and it does the auto sorting, I want the rows from D to F in Sheet1 to carry along with repositioning that comes from Sheet3. I hope I did manage to explain properly what I want.
I've tried without success to make it work; I can't figure out the proper way of doing this, especially due to the fact that Sheet1 table has different range.
I figured out how to fix the issue so I'll post the code here. Basically whenever you edit the column that you choose to sort by in Sheet3 (master sheet) it will first copy in the Sheet1 (target sheet) what changes you've made in A & B columns and then it will sort both sheets at the same time, this way the data from following columns in Sheet1 will carry along.
I used A & B columns in this example, since that's what I commented above, but can be different ranges as long as they're similar in size.
// Master Sheet Settings (Copy ranges must be similar in size)
var msName = 'Master Sheet';
var msSortCol = 4; // which column to trigger the sorting when you edit
var msSkipRows = 6; // how many rows to skip, if you have header rows
var msCopyRange = 'A7:B51'; // the range you want to copy
// Target Sheet Settings
var tsSortCol = 3;
var tsSkipRows = 10;
var tsName = 'Target Sheet';
var tsCopyRange = 'A11:B55';
var sortAscending = true;
var activeSheet;
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var editedCell = ss.getActiveRange().getColumnIndex();
if (ss.getSheetName() == msName) {
activeSheet = SpreadsheetApp.getActiveSheet();
if (editedCell == msSortCol) {
copyRow();
autoSort(activeSheet);
}
}
}
function copyRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(msName);
var values = sheet.getRange(msCopyRange).getValues();
ss.getSheetByName(tsName).getRange(tsCopyRange).setValues(values);
SpreadsheetApp.flush();
}
function autoSort() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var msheet = ss.getSheetByName(msName);
var tsheet = ss.getSheetByName(tsName);
var mrange = msheet.getDataRange();
var trange = tsheet.getDataRange();
if (ss.getSheetName() == msName) {
if (msSkipRows > 0) {
mrange = mrange.offset(msSkipRows, 0, (mrange.getNumRows() - msSkipRows));
}
if (tsSkipRows > 0) {
trange = trange.offset(tsSkipRows, 0, (trange.getNumRows() - tsSkipRows));
}
mrange.sort({ column: msSortCol, ascending: sortAscending });
trange.sort({ column: tsSortCol, ascending: sortAscending });
}
}

Google sheets, get range of rows, where column intersect cell is empty

Basically I want to use an auto-sorting script through the script editor in Google sheets, but I want it to smartly pick a range of rows, by only selecting those rows where a specific column has an empty cell.
All other rows that have that column's cell populated would stay put. Here is the sort code I've found.
/**
* Automatically sorts the 1st column (not the header row) Ascending.
*/
function onEdit(event){
var sheet = event.source.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
var tableRange = "A2:T99"; // What to sort.
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}
Thanks.
Note: this will only sort the values in the cells (metadata such as formats, notes etc will not be sorted, as they would with the GAS range.sort() method).
function onEdit(event)
{
var sheet = event.source.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 0; // zero-based index
if (editedCell.getColumn() == columnToSortBy)
{
var columnToWatch = 5; // checking this column for blank cells (zero-based index)
var tableRange = "A2:T99"; // what to sort
var range = sheet.getRange(tableRange);
var data = range.getValues();
var dataCopy = data.slice();
dataCopy.sort(function(a, b) {return a[columnToSortBy] > b[columnToSortBy] ? 1 : (a[columnToSortBy] < b[columnToSortBy] ? -1 : 0);});
var j = -1;
for (var i = 0, length = data.length; i < length; i++)
{
if (data[i][columnToWatch].toString().length)
{
do j++; while (!dataCopy[j][columnToWatch].toString().length);
data[i] = dataCopy[j];
}
}
range.setValues(data);
}
}

Resources