Autosort not working anymore: Google spreadsheet - sorting

I have a working script on an old version of a Google spreadsheet that isn't working any more.
It was a sorting script which sorts out the rows each time one or more column is modified.
On the new spreadsheet that isn't working any more. I'm trying to figure out why but I can't catch where the error is.
Can anyone help?
function onEdit(e) {
Logger.clear()
Logger.log('Script Start')
var ss = SpreadsheetApp.getActiveSpreadsheet();
Logger.log('ss=%s', ss)
var sheet = ss.getSheets()[0];
Logger.log('sheet=%s',sheet)
Logger.log('SheetName=%s',sheet.getName())
if(sheet.getName()=='MembriForum'){
var editedCell = sheet.getActiveCell();
Logger.log('editedCell=%s', editedCell)
}
var columnToSortBy_1 = 4;
var columnToSortBy_2 = 6;
var range = sheet.getDataRange();
Logger.log('range=%s', range)
if(editedCell.getColumn() == columnToSortBy_1 || editedCell.getColumn() == columnToSortBy_2){
var range = sheet.getRange(range.getRow()+1, range.getColumn(),range.getNumRows()-1,range.getNumColumns() );
Logger.log('range=%s', range)
range.sort([{ column: columnToSortBy_1, ascending: true }, { column: columnToSortBy_2, ascending: true}]);
}
}

I think this is unfortunately due to an issue in new spreadsheets...
See here for details and star it to (hopefully) get more attention from Google.
Your condition will never be true since editedCell.getColumn() will always be 1.

Related

google form script exclude sundays on dates choices

im making a script for making an apointment. I get the choices of appointmentt date from my spreadsheet using script. How to exclude sunday when i get the choices from my spreadsheet ? i cant find a way to remove the sunday.
here is the code
var ssID = "1hil07Z2wvTXH1szX9bNfPKVLDQVO36ACQFGOU6_VUI0";
var formID="1SD5BenAnNxNz-wtw0YPut6YdTf7a62zHn_z3VrTdTUU";
var wsData = SpreadsheetApp.openById(ssID).getSheetByName("DATA");
var form = FormApp.openById(formID);
function main(){
var labels = wsData.getRange(1,1,1,wsData.getLastColumn()).getValues()[0];
labels.forEach(function(label,i){
var options = wsData
.getRange(2, i+1,wsData.getLastRow()-1,1)
.getDisplayValues()
.map(function(o){return o[0]})
.filter(function(o){return o !== ""})
//Logger.log(options);
updateDropDownUsingTitle(label,options);
});
}
function updateDropDownUsingTitle(title,values) {
var title = "Tanggal Penjemputan";
var items = form.getItems();
var titles = items.map(function(item){
return item.getTitle();
});
var pos = titles.indexOf(title);
var item = items[pos];
var itemID = item.getId();
updateDropdown(itemID,values);
}
function updateDropdown(id,values) {
var item = form.getItemById(id);
item.asListItem().setChoiceValues(values);
}
this is the form
THis is my spreadsheet
There are 3 ways to achieve your goal:
Use a non-Sunday formula in sheet
Add a weekday column to sheet and filter in script
getValues and new Date instead of getDisplayValues, filter Sunday and then Utilities.formatDate
You can use the following formula:
=ArrayFormula(TODAY()+FILTER({1;2;3;4;5;6;7}, WEEKDAY(TODAY()+{1;2;3;4;5;6;7})<>1))
See on Google Sheets
This will give you the next 7 days excluding Sunday.

Suitescript Saved Search Filter using other saved search results

I am trying to use the results of a specific saved search to try and filter another saved search in suitescript.
Basically, there is a button created on a project. Once the button is clicked, I need to go get all the tasks for that specific project and use each task to filter on a transaction saved search using a custom field and get whatever information is on that saved search.
This is what I have so far:
function runScript(context) {
var record = currentRecord.get();
var id = record.id;
var type = record.type;
var i = 0;
console.log(id);
var projectSearch = search.load({id: 'customsearch1532'})
var billableExpenseSearch = search.load({id: 'customsearch1533'})
var projectFilter = search.createFilter({
name:'internalId',
operator: search.Operator.IS,
values: id
});
projectSearch.filters.push(projectFilter);
var projectResults = projectSearch.run().getRange(0,1000);
while(i < projectResults.length){
var task = projectResults[i].getValue(projectSearch.columns[1]);
console.log(task);
var billableExpenseFilter = search.createFilter({
name:'custcol4',
operator: search.Operator.ANYOF,
values: task
});
billableExpenseSearch.filters.push(billableExpenseFilter);
var billableExpenseResults = billableExpenseSearch.run().getRange(0,1000);
console.log(billableExpenseResults.length);
for(var j = 0; j< billableExpenseResults.length; j++){
var testAmount = billableExpenseResults[j].getValue(billableExpenseSearch.columns[3]);
console.log(testAmount);
}
i++;
}
}
The log for the Task is correct. I have 2 tasks on the project I am trying this on but once we get to the second iteration, the billableExpenseSearch length is showing as 0, when it's supposed to be 1.
I am guessing that my logic is incorrect of the createFilter function doesn't accept changes once the filter is created.
Any help is appreciated!
EDIT:
var billableExpenseSearch = search.load({id: 'customsearch1533'});
var billableExpenseFilter = search.createFilter({
name:'custcol4',
operator: search.Operator.ANYOF,
values: task
});
billableExpenseSearch.filters.push(billableExpenseFilter);
var billableExpenseResults = billableExpenseSearch.run().getRange(0,1000);
console.log(billableExpenseResults.length);
for(var j = 0; j< billableExpenseResults.length; j++){
var taskid = billableExpenseResults[j].getValue(billableExpenseSearch.columns[0]);
console.log(taskid);
Thank you
I think your guess is correct your are keep pushing filters
billableExpenseSearch.filters.push(billableExpenseFilter);
After pushing the filter and extract the value you need to remove it before adding a new one, you can do this by pop() the last one:
billableExpenseSearch.filters.pop();
Note: You can fix this by re-loading the search every time before pushing the filter. this will reset your filters, but I do NOT recommend that since loading a search will consume more USAGE and might receive USAGE_LIMIT_EXCEEDED ERROR.
I also recommend the following:
1- Get all task ids before doing the second search, once you do that you only need to search once. Because if you have many records you might encounter USAGE_LIMIT_EXCEEDED ERROR. Since you work with a client or Suitelet script you only have 1000 USAGE.
Edit: Sample might help you.
var ids = [];
var pagedData = projectSearch.runPaged({pageSize : 1000});
// iterate the pages
for( var i=0; i < pagedData.pageRanges.length; i++ ) {
// fetch the current page data
var currentPage = pagedData.fetch(i);
// and forEach() thru all results
currentPage.data.forEach( function(result) {
// you have the result row. use it like this....
var id = result.getValue(projectSearch.columns[1]);
Ids.push(id);
});
}
Note: This search will extract all records not only first 1000.
After that add the array to the Filter
var billableExpenseFilter = search.createFilter({
name:'custcol4',
operator: search.Operator.ANYOF,
values: [ids]
});
2- Don't Use search.load use search.create it will make your script more readable and easier to maintain in the future.

A simple sort script on Google Sheets is not working

I have a "leaderboard"/"scoreboard", across four sheets, that I need to have auto sorting whenever updated by first Total Score (column 2) and then Total Kills (column 3). These columns are the same across all four sheets.
I've used a very simple script in the past when the scoreboard was limited to one sheet, but I have since expanded it to have Top Ten, Top Four, and Top Two on separate sheets within the same document.
The problem I'm running into: When the script updates one sheet, the other ones seem to flat out stop working entirely; in other words, the script breaks.
Can I please get some advice? I've tried several scripts already from this site, and the basic one I see some success with (but then the script seemingly breaks?) is below.
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MAIN EVENT");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TEN");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP FOUR");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TWO");
sheet.sort(3, false).sort(2, false);
}
Ideally, when functioning, the sheets will literally just sort themselves by the Total Score column, with Total Kills being the "tiebreaker" for sorting.
I've included a copy of my sheet if anybody could help:
https://docs.google.com/spreadsheets/d/1a6XGv09TPt5Vnxqfcd1Xba3TGMis5OelGxlvzNDl5CY/edit?usp=sharing
try something like this instead of your scripts:
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet().getName()
var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Sheet1"){
var columnToSortBy = 2;
var tableRange = "A3:C10"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}}
else if(sheet=="Sheet2"){
var columnToSortBy = 7;
var tableRange = "A3:C10"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
else{return}
}}
try this:
function sortOnEdit(e) {
var sh=e.range.getSheet();
var name=sh.getName();
var incl=['MAIN EVENT','TOP TEN','TOP FOUR','TOP TWO'];
if(incl.indexOf(name)==-1) return;
sh.sort(3,false).sort(2,false);
}

My google script is slowing down my spreadsheet very badly

I'm a total beginner when it comes to writing scripts but somehow managed to copy-paste/write this script that protocols the date when a specific cell has been updated. Somehow the script slows down my spreadsheet so badly that I have to wait a few seconds for every change I make. I used the s.getRange() function instead of s.getActiveCell() because in some cases I want to change up to 30 cells at once and it should then protocol all the changes. Could this maybe slowdown my sheet? Or does anyone have other ideas how I can speed up my sheet?
Why I entered the following functions:
(r.getRow() !1 & r.getRow() !=2) so that the 2 title rows can be change without being protocoled
var name1versandstatus = s.getRange("datum1versandspalte") so that I can insert new columns without affecting the scripts function
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Strukturierung" ) {
var r = s.getActiveRange(); //
if ( r.getRow() !=1 & r.getRow() !=2) {
var name1versandstatus = s.getRange("datum1versandspalte")
if( r.getColumn() == name1versandstatus.getColumn()) {
if(r.getValue() == "Versendet"){
var nextCell = r.offset(0, 1);
nextCell.setValue(new Date());
}
}
}
}
}

Appcelerator Store Local Searches

When a button is pressed, I would like the id and the name of the button saved locally.
I am not quite sure the best way to approach this problem. Should I use appcelerator properties (http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.App.Properties) or write to a file to storage? At the moment I am using the Ti.App.Properties.setList.
Example code:
searchStorageName = "searchHistory";
searchResultsArray = [];
var currentEntries = (Ti.App.Properties.getList(searchStorageName));
// Create search entry object.
var localSearchObject = {
company_name: resultNodeCompany,
company_id: resultNodeCompanyID,
variation_id: resultNodeCompanyVariationID
};
// Check if existing entries, if so push current search
// and previous searches to array.
if(currentEntries === null || currentEntries === undefined){
searchResultsArray.push(localSearchObject);
Ti.App.Properties.setList(searchStorageName, searchResultsArray);
// searchResultsArray.push(localSearchObject, currentEntries);
}
else {
searchResultsArray.push(localSearchObject, currentEntries);
Ti.App.Properties.setList(searchStorageName, searchResultsArray);
}
I am stuck at the moment as it is inserting duplicate searches into the array. When I loop over the values to create a list in the UI it shows duplicates.
var currentEntries = (Ti.App.Properties.getList(searchStorageName));
var currentEntriesLength = currentEntries.length;
var getPreviousHistorySearchesArray = [];
currentEntries.forEach(function(entry, index) {
var company_name = entry.company_name;
var company_id = entry.company_id;
var variation_id = entry.variation_id;
// Create View Entry.
createSearchHistoryViewEntry(index, company_name, company_id, variation_id);
}
Use SQLite_Database Better than local properties http://docs.appcelerator.com/titanium/3.0/#!/guide/Working_with_a_SQLite_Database

Resources