getMonth problem with Google Sheets javascript - javascript

getMonth is not a function in this code for Google Sheets:
... Logger.log(ss.getSheetByName("Rendimentos").getRange(aportes-cont,3).getValue().getMonth());
while (ss.getSheetByName("Rendimentos").getRange(aportes-cont,3).getValue().getMonth()===numMes){ ... }
The Logger.log line works perfectly. It shows the number of the month required. But the second line show a message error: getMonth() is not a function.
It just don't make sense the same code works inside the Logger.log, but get stucked inside the while loop.
I don't know what to do.

The error occurs when the original cell does NOT contain the date. In this case, the .getMonth() method tries to determine the month from a value that is not the date.
Try replacing your code with the following:
let rangeData = ss.getSheetByName("Rendimentos").getRange('C:C').getValues().flat();
while (new Date(rangeData[aportes-cont]).getMonth()===numMes){
...
}
It is also good practice to reduce the number of times the script accesses the google sheets data - so in the suggested code I first read the data of the entire column C once, and then work with the resulting data as elements of an array

Related

Script for last edited/modified time & date

I have been searching around for a script that will give me the time & date that a google sheet was last modified.
I have a list of all the google sheet workbook IDs in column E of a sheet called 'Planner Directory' and I would like it to return the time & date last modified in column F.
This would be really helpful if anyone can assist?
Since you already have all the data in a Google Sheet, I think the easiest way to get this working automatically is using Google Apps Script. I will leave an example of how it would work.
Try this code:
function myFunction() {
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet20"); // Change it to the name
// of the sheet you. are using
var range = ss.getDataRange();
var values = range.getValues();
for(var i=1; i<values.length; i++)
{
values[i][1] = lastModifiedTime(values[i][0]); // 0 is the column number in my testing sheet
// where the IDs are.
// 1 is the column number where the time will be.
}
range.setValues(values);
}
function lastModifiedTime(id)
{
var file = DriveApp.getFileById(id);
return file.getLastUpdated();
}
Input data:
Replace the Sheet ID fields with valid IDs.
Result:
Remember to change the format of the column where you want you have the last modified time to Number > Date time.
Now, in order for you to automate this script you can use a time-driven trigger from Google Apps Script so that the script runs every 5, or 10 minutes for example and so that you can always get the latest time in the results.
Trigger:
References:
Method: getLastUpdated()
Time-driven triggers
I was able to use the suggested script to get the last modified date of a file, which is great but I am having two issues. In the next column of the spreadsheet I had a formula which would tell me if the last modified date is today's date. =if(C2=Today(),"Updated","Not Updated")
The formula doesn't recognize the last modified date that is entered by the script, even though I have that column format set to Date.
When the script suggested in this thread runs, it wipes out the formula entirely and replaces it with static text.

How to make google app script - calendar createEvent() to accept GSheet inputs from cells populated using array formula

A few days ago I got help from Stack Overflow to modify my then Apps Script code used to make calendar events from info on Google sheet, so as to tick a checkbox whenever an entry from the corresponding row is made and subsequently make new events only when the checkbox is unticked.
function addEvent() {
let webinarCalendar = CalendarApp.getCalendarById("blablablablablabla#gmail.com");
let calendarSheet = SpreadsheetApp.getActiveSheet();
let schedule = calendarSheet.getDataRange().getValues();
schedule.splice(0, 1);
const k = 16; // colIndex of checkbok col
const created = schedule.map(e => [e[k]]);
schedule.forEach(function(entry, i) {
if (entry[k] == true) { return; }
webinarCalendar.createEvent(entry[3], entry[14], entry[15], {description: entry[13]});
created[i][0] = true;
});
calendarSheet.getRange(2, k + 1, created.length, 1).setValues(created);
}
This current code worked just fine until 2 days ago when I updated 3 of the 4 cells with the required inputs to work on an array formula so that they get populated automatically whenever a new row entry is made.
The error on the app script console says :
Exception: The parameters (String,String,String,(class)) don't match the method signature for CalendarApp.Calendar.createEvent.
The parameters required for this createEvent() as per documentation are title(string), start time(string), finish time(string) and description(which is inside a javascript object I think and is also a string). To ensure that the datatype did not somehow get changed in the process of creating array formula, I cross checked the cells with an ISTEXT() and all of the inputs returned TRUE.
Second trial that I made was to change the splice() from (0,1) to (0,2) so that it ignores the first row which has the array formula written into the cells, which also did not fix the issue.
I would greatly appreciate if someone could show me what is causing this issue and help me fix it.
I don't know why it worked previously, but startTime and endTime should be Date.
I have checked that you columns are String.
Reference:
createEvent(title, startTime, endTime, options)
The error on the app script console says : Exception: The parameters (String,String,String,(class)) don't match the method signature for CalendarApp.Calendar.createEvent.
This is simply saying it's reading from data that is not in the proper data type. In this case, perhaps, try encasing the entries with 'new Date(entry[x])' for the respective start and end date/time entries.
For people trying to run the scripts, one underlying cause might be the fact that you may be using US locale when the date have been formatted as UK.
(e.g. Date that App Script is looking for is mm/dd/yyyy tt:tt:tt, but if you click in the formula cell it shows as dd/mm/yyyy tt:tt:tt)
What you would do is to go to Files > General > Locale > (Country of Choice) > Save settings.
You would then reload the page and try if the script is working now without that "Cannot find method createEvent(string,string,string)" error.
The line of code to use in your script would be:
SpreadsheetApp.getActive().setSpreadsheetLocale('en_UK');
You could include it in your onOpen trigger function.

Google sheet script to add a week to a date from the sheet

Sorry - I'm a newbie!
I need to use a script to read a date from a Googlesheet, add a week and save the new date back to the sheet.
I've tried various suggestions from various posts without success. The approach I thought should work is failing to get a millisecond value from a date from a cell - subsequent processing appeared OK.
var oldDate = sheet.getRange('oldDateRange').getValue(); // obtains a date object and then...
var oldDateValue = oldDate.getMilliseconds() // I expected to return milliseconds but shows as undefined...
See link to a simplified illustration sheet and script illustrating my problem.
This is my first question on StackOverflow - feedback welcome on how to make it more helpful for others....
In order to convert the date obtained from the sheet to milliseconds, I think you simply need to replace .getMilliseconds() with .getTime()

Handling date format in Pentaho using javascripting

My input excel sheet has field "date" with two different types of values as shown below
2015-03-02 11:06:35
3/2/2015 4:03:53 AM
I am reading them as "string" and performing below logic
var temp = date.getString();
temp = str2date(temp,"dd.MM.yyyy HH:mm:ss");
I get the below error
*Could not apply the given format dd.MM.yyyy HH:mm:ss on the string for 2015-03-02 11:06:35 : Format.parseObject(String) failed*
I tried reading them as "date" , but I got the below error
Unparseable date: " 2015-03-02 11:06:35 "
How can we handle this error?
A couple ideas from the docs. http://wiki.pentaho.com/display/EAI/JavaScript+Values
First try calling getDate() it should be a function associated with the cell in question.
If that doesn't work try calling getNumber() in excel all dates are represented in floating point. The whole number part is days since jan 1 1970 and the fraction part is the percentage of the way through the day. I'm sure if you look around there is a js wrapper around this functionality.
Another idea would be to determine all the numberformat strings. Loop over them catching errors. The one that doesn't throw an error should be the correct one. Or you could write a small regex pattern to better examine the dates coming out.
Finally, I got result. I will explain step by step please follow steps very carefully.
Step 1: Data Grid => I created one field called fail_date i.e String datatype.
Step 2: Modified Java Script Value => I wrote some code like these.Please follow screen shot.
Step 3: Select values => Here i converted date datatype.
Step 4: Modified Java Script Value 2 => Here also i wrote one code.Please follow screen shot.
Step 5: Select values => Finally, I converted require data format.here correct_date field is your required output.
Step 6: Final output screen will be like these.
Step 7: Below screen shot show whole transformation screen.
Hope this helps.
Can you use a library. I've used xdate its really good. And it parses both of these date strings
var xdate = require('xdate');
xdate('2015-03-02 11:06:35').toDate(); // returns a js date object
xdate('3/2/2015 4:03:53 AM').toDate(); // returns another js date object.

Google Spreadsheet Custom Function: Too many scripts running

I am trying to create a custom method in Google Spreadsheet. I have the following method to replace the missing WEEKNUM method. (I leave to second parameter in order to allow upload of excel files.)
function WEEKNUM(inDate, dummy){
return Utilities.formatDate(inDate, "GMT", "w");
}
I call in method in approximately 400 rows twice (800 times) in one spreadsheet. Some of the formulas complete however for other I get this error message.
error: There are too many scripts running simultaneously for this Google user account.
Is there anything I can do to fix this? I understand 800 executions it a lot but not anymore than would be expected of built in functions. I know there are alternative ways to calculate the week number (such as =LEFT(TEXT(A2; "w d"); 2)) however I want to know if it is even possible to create custom formula functions that wont be subjected to this invisible ceiling.
Thank you in advanced for your replies.
Have you custom function receive a range and output an array. No need to use an arrayformula, which also wont work on a custom function
Have you tried an ArrayFormula? In your spreadsheet, instead of having 800 calls to:
=WEEKNUM(-cell-, -dummy-)
in cells A1 to B400, try:
=ARRAYFORMULA(WEEKNUM(A1:B400, -dummy-))
in cell A1.

Categories