Open google spreadsheet at date - date

I have created a google spreadsheet. On the column A in row 1 I have used "vastzetten" (that's in dutch). The first column and row I have blocked. When I go with the cursor I can change the date and the rest of the sheet dissapeared after the block. (Look the images). Is there a way when I start the sheet it selects the date of the day then moves the rest of the sheet after the titleblock? I hope that somebody knows what I mean.

You could use an installable trigger to hide columns and/or to activate the range corresponding to the current date.
For instructions on how to set an installable trigger see https://developers.google.com/apps-script/guides/triggers/installable
The following code assumes that the column headers are values of date type. If the current date is found, then the columns at the left will be hidden and the the cell below the corresponding header will be activated.
function myFunction(){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheets()[0];
var tz = ss.getSpreadsheetTimeZone();
var today = Utilities.formatDate(new Date(), tz, 'YYYY-MM-dd')
var data = sheet.getDataRange().getValues();
var headers = data[0];
for(var i = 0;i<= headers.length;i++){
if(headers[i] instanceof Date){
if(today == Utilities.formatDate(headers[i], tz, 'YYYY-MM-dd')){
sheet.hideColumns(2,i-1);
sheet.getRange(2, i+1).activate();
break;
}
}
}
}

Related

App Scripts stepping months and date formatting

I'm new to App Script, please be gentle!
I have a table with a start date and a number of months, I need to list each recurring month from the start date to the number of months.
I'm struggling with 2 issues:
The first date placed in the array seems to be updating as I cycle the dates
The formats are in UNIX and I can't get them to be useful despite an awful lot of reading!
Thank you so much for any help!
Input file (https://i.stack.imgur.com/2EJ65.png)
Output file(https://i.stack.imgur.com/0DH5R.png)
Console log (https://i.stack.imgur.com/NVqck.png)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get Data sheet
var rawData = ss.getSheetByName('Sheet3');
// Get a date and set it as a date format
var start = new Date(rawData.getRange("B2").getValues());
console.log(start);
// Get Months
var months = rawData.getRange("C2").getValues();
// Define dates array
var dates = [];
// Add first date
const startDate = start
dates.push([startDate]);
//Add rest of dates dates in a loop
for (var run = 1;run < months;run++) {
//get the last pasted month name
var lastMonth = start.getMonth();
//push next month
dates.push([start.setMonth(lastMonth+1)]);
}
// Get processedData sheet
var processedData = ss.getSheetByName('sheet2');
// Post the outputArray to the sheet in a single call
console.log(start);
console.log(startDate);
console.log(dates);
console.log(dates.length);
console.log(dates[0].length);
processedData.getRange(1,1,6,1).setValues(dates);
}
Incrementing Dates by month and setting format
function lfunko() {
const ss = SpreadsheetApp.getActive();
let dt = new Date();
let start = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate());//need to change back to your value
const months = 10;//need to change back to your value
let dates = [];
dates.push([start]);
for (let run = 1; run < months; run++) {
dates.push([new Date(start.getFullYear(),start.getMonth() + run, start.getDate())])
}
ss.getSheetByName('Sheet0').getRange(1, 1, dates.length).setValues(dates).setNumberFormat("mm/dd/yyyy");//changed sheet name
Logger.log(dates);
}

apply FilterCriteria "whenDateEqualToAny(dates)" - What is the correct form of the date array (dates) to parse?

I want to add some quick filters using the ui of google sheets. Currently I want to allow the user to click "show last month" to only see the data of the last month. The dates are written in the first column.
Now I prefer to use the filter of google sheets before just printing the values into the sheet, to allow the user to further modify that filter.
Thus I am trying to build filterCriteria using SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates) and I am parsing an array of valid dates. In the documentation it says I have to put a "Date[]" - doesn't that mean an array of dates?
Below the error message and my code:
Error message (linked to the line "var filterCriteria..."):
"Exception: The boolean condition can not have multiple values for equality checks for non-data source objects"
My code:
function showLastMonth() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName('evaluation')
var now = new Date()
var thisYear = now.getFullYear()
var thisMonth = now.getMonth()
if(thisMonth == 0){var startMonth = 11; var startYear = thisYear - 1}
else{var startMonth = thisMonth - 1; var startYear = thisYear}
var startDate = new Date(startYear, startMonth, 1)
var endDate = new Date(thisYear, thisMonth, 0)
var dates = getDateArray(startDate, endDate)
var filter = sheet.getFilter()
if(filter == null ){
var range = sheet.getDataRange()
var filter = range.createFilter()
}
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
filter.setColumnFilterCriteria(1, filterCriteria)
}
getDateArray = function(startDate, endDate){
var startYear = startDate.getFullYear()
var startMonth = startDate.getMonth()
var dateArray = []; dateArray.push(startDate)
var date = startDate; var day = date.getDay()-1
while(date<endDate){
day++
date = new Date(startYear, startMonth, day)
if(date<=endDate){dateArray.push(date)}
}
return dateArray;
}
I believe your goal as follows.
You want to hide the rows of the values except for dates using the basic filter.
You want to achieve this using Google Apps Script.
Issue and workaround:
In the current stage, it seems that array of whenDateEqualToAny(array) is required to be the length of 1. I think that this is the reason of your issue. So for example, when var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny([dates[0]]) is used, no error occurs. This situation is the same with the setBasicFilter request of Sheets API. Unfortunately, it seems that this is the current specification. But, the official document says The acceptable values. which uses the plural form. Ref So I also think that this is not correct for the actual situation as mentioned by TheMaster's comment.
In order to achieve your goal, in this case, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, using setHiddenValues(), the values except for the values of dates in your script are set as the hidden values.
Modified script:
When your script is modified, please modify as follows.
From:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
To:
var obj = dates.reduce((o, e) => Object.assign(o, {[`${e.getFullYear()}\/${e.getMonth() + 1}\/${e.getDate()}`]: true}), {});
var range = sheet.getRange("A1:A");
var dispValues = range.getDisplayValues();
var hiddenValues = range.getValues().reduce((ar, [a], i) => {
if (a instanceof Date && !obj[`${a.getFullYear()}\/${a.getMonth() + 1}\/${a.getDate()}`]) {
ar.push(dispValues[i][0]);
}
return ar;
}, []);
var filterCriteria = SpreadsheetApp.newFilterCriteria().setHiddenValues(hiddenValues).build();
Pattern 2:
In this pattern, using whenNumberBetween(), the values of dates in your script are shown. In this case, it is required to convert the date object to the serial number.
Modified script:
When your script is modified, please modify as follows.
From:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
To:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenNumberBetween(
(dates[0].getTime() / 1000 / 86400) + 25569,
(dates.pop().getTime() / 1000 / 86400) + 25569
).build();
The conversion from the date object to the serial number was referred from this thread.
References:
setHiddenValues(values)
whenNumberBetween(start, end)

Inputting Date without time

Using the code below, the google sheet enters the Date in column 6 when a cell in column 1 is edited. It also includes the timestamp.
How can this code be altered so that just the date (day-month-year) is entered? This would allow searches by date on the sheet.
function onEdit(e) {
var sheetName = 'Cases Allocation'; //name of the sheet the script should work on
var colToWatch = 1
var colToStamp = 6 //timestamp in col A
if (e.range.columnStart !== 1 || e.source.getActiveSheet()
.getName() !== sheetName || e.value == '') return;
var writeVal = e.value !== "" ? new Date(),: '';
e.source.getActiveSheet()
.getRange(e.range.rowStart, colToStamp)
.setValue(writeVal);
}
You can try using Utilities.formatDate. This method formats date according to specification described in Java SE SimpleDateFormat class. You can visit the date and time patterns here. An example of usage is:
// This formats the date as Greenwich Mean Time in the format
// year-month-dateThour-minute-second.
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);
Do take note that using Utilities.formatDate has the following effects as noted in this post:
Utilities.formatDate does not change the cell format; it converts
its content to text. If you are going to use the date value in
computations, you don't want it to be converted to text.
Utilities.formatDate requires one to specify a timezone. If you put
something like "GMT+1" and your country observes Daylight Saving
Time, you can expect hard-to-track bugs to come up a few months
later. With setNumberFormat, the date value remains consistent with
all other date values in the spreadsheet, governed by its timezone
setting.
To avoid these, you can also use setNumberFormat(numberFormat) to set the date or number format. The accepted format patterns are described in the Sheets API documentation. And an example usage is:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("B2");
// Always show 3 decimal points
cell.setNumberFormat("0.000");
Thanks all - tried format etc, but then just decided to add a column and split the date and time, with just the date going into a new column.
function onEdit(e) {
var sheetName = 'Cases Allocation'; //name of the sheet the script should work on
var colToWatch = 1
var colToStamp = 6 //timestamp in col A
if (e.range.columnStart !== 1 || e.source.getActiveSheet()
.getName() !== sheetName || e.value == '') return;
//var writeVal = e.value !== "" ? new Date(),: '';
e.source.getActiveSheet()
.getRange(e.range.rowStart, colToStamp)
.setValue(new Date(new Date().setHours(0,0,0,0))).setNumberFormat('MM/dd/yyyy');
}
The below code will save the date without time. You can change the format as required. The field remains a date which can be used as required.
setValue(new Date(new Date().setHours(0,0,0,0))).setNumberFormat('MM/dd/yyyy');

Google Apps Script using wrong date format in excel

So I am working on a Google Apps script that pulls an email address, subject, and body from a Google sheet file. This info is used to send an email out. Right now in my Subject column for the Google Sheets file I have =TODAY() so that the date is pulled. My script updates this column everyday so the date is always current.
The issue is that when the email comes the subject line shows
"Sat Aug 11 2018 00:00:00 GMT-0700 (PDT) "
Instead of...
08/11/18 like its setup for in Google Sheets
Not sure why this could be, My code is below.
/**
* Creates a two time-driven triggers.
*/
function createTimeDrivenTriggers() {
// Trigger every 6 hours.
ScriptApp.newTrigger('adddate')
.timeBased()
.atHour(21)
.everyDays(1)
.inTimezone("America/Los_Angeles")
.create()
ScriptApp.newTrigger('sendEmails2')
.timeBased()
.atHour(22)
.everyDays(1)
.inTimezone("America/Los_Angeles")
.create()
}
/**
* This is my hacky way to make sure sheets has today's date.
*/
function adddate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var cell = sheet.getRange(2,2);
cell.setValue('=TODAY()');
}
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'SUCCESSFULLY SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var subject = row[1]; // Second column
var message = row[2]; // Third column
var emailSent = row[3]; // Fourth column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
The problem you are encountering is that your cell is formatted as a date and you are passing it as a parameter that expects a string. At that point you are no longer controlling the conversion, and you are getting way more than you wanted. Two ways to address it.
1) Make it a string in the first place with
cell.setValue('=text(TODAY(),"mm/dd/yy"');
which does run the risk of ruining any date processing you do on it at first (though I see none, so probably fine).
So probably better is (not 1, just this)
2) is to get the displayed string while leaving the underlying date like you had it with var subject = row[1].getDisplayValue();
2) has the added benefit of going with the date format for which sheets is set up.

Stock Inventory - Send email when cell value < 2 (Google Spreadsheet)

I currently trying to create for stock inventory of some products that are frequently used in my workplace using google spreadsheet. Moreover, I'm trying to come up with a script that would send me an email when a certain product reaches a value below 2 so that I would know that a certain product needs to be restock. I'm do not know the basics of coding, but here's what I got so far:
function readCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var ProductA = sheet.getRange("B2").getValue();
var Product B = sheet.getRange("B3").getValue();
var min = 2
if (ProductA<min) MailApp.sendEmail('n********#googlegroups.com', 'LOW REAGENT STOCK', 'Attention! Your stock of ProductA is running low. Please proceed to restock.');
if (ProductB<min) MailApp.sendEmail('n********#googlegroups.com', 'LOW REAGENT STOCK', 'Attention! Your stock of ProductB is running low. Please proceed to restock.');
}
I put the trigger on onEdit to run the script and I intent to expand the list with more products. The thing is that if one product as already reached a value below 2 and if a change another one, the script will send email for both of them. With more products, this becomes a nuisance, because I would received a bunch of emails if other values remain below 2. Can someone help me out with this? I couldn't find any solution to this so far and I would truly appreciate some help.
Thank you!
When the "onEdit" trigger fires, it receives the event object as parameter containing some useful information about the context, in which the edit action occurred.
For example,
function onEdit(e) {
// range that was edited
var range = e.range;
//value prior to the edit action
var oldValue = e.oldValue;
//new value
var value = e.value;
//sheet the action came from
var sheet = range.getSheet();
//cell coordinates (if edited range is a single cell)
//or the upper left boundary of the edited range
var row = range.getRow();
var col = range.getColumn();
}
You can inspect the event object to get the cell that was edited and see if it's in column B.
var productsColIndex = 1; //column A index;
var inventoryColIndex = 2; //column B index
var range = e.range;
var value = e.value;
var sheet = range.getSheet();
var editedRow = range.getRow();
var editedCol = range.getColumn();
var productName = sheet.getRange(editedRow, productsColIndex).getValue();
//checking if
//1) column B was edited
//2) the product exists in column A
//3) new value is less than 2
if ((editedCol == inventoryColIndex) && productName && value < 2) {
//code for sending notification email.
}
Finally, because simple triggers like onEdit() can't call services that require authorization, it's better to create a function with a different name and then set up the installable trigger manually. In your Script Editor, go to "Edit" -> "Current project's triggers" -> "Add a new trigger" , select your function name from the dropdown list, and pick the following options: "From spreadsheet", "On edit".