Apps Script: setting one formula for a whole column - date

I'm working on an Apps Script project for Sheets and I don't know if it's because I just never really worked with Sheets or Excel, but I don't know how to set a formula for a whole column through code.
var cell = sheet.getRange([i], 2);
var cell2 = sheet.getRange([i], 1);
var inhoud = cell2.getValue();
cell.setFormula("=(" + inhoud/86400000 + "DATE(1970,1,1)");
I want every B of a row to do something with the A of that same row. In the sheet self it's easy to just "drag the function down", to make it apply to every row, but I don't know how to get that to work in code as I can't use A2, for example, or A2:A30. Part of the problem may be that it's in a for loop:
var subsie = [];
for (i = 0; i < subscriptions.length; i++) {
var subscription = subscriptions[i];
creationdate = subscription.creationTime;
if (subscription.plan.planName == 'ANNUAL' && subscription.renewalSettings.renewalType == 'AUTO_RENEW') {
subsie.push([creationdate, ' ', subscription.plan.planName]);
Logger.log(subsie);
var cell = sheet.getRange([i], 2);
var cell2 = sheet.getRange([i], 1);
var inhoud = cell2.getValue();
cell.setFormula("=(A1:A100/86400000) + DATE(1970,1,1)");
} }
sheet.getRange(sheet.getLastRow()+1, 1, subsie.length, subsie[0].length).setValues(subsie);
The actual goal is to convert the epoch values of A into dates, which I tried in a lot of different ways but turned out to be more difficult than I expected. This was the only formula that seemed to work for my output, which was like this: 1433235478178. How can I make this code work? Thanks in advance!

Solved it :)
creationdate = (subscription.creationTime/86400000)+25567;

Related

Google script - send email alert

I have a script that looks into values in column G and if the correspondent cell in column A is empty, sends me an email.
--- WHAT WORKS --
It works ok for static values: it sends one email per each not empty cell in column G for which there is no value in column A
--- WHAT DOESN'T WORK --
It sends several emails for what I assume it's every Column G cell (empty or not) when the column A values are fetched from another tab. That way it's like all G and A cells have data, so I get multiple unwanted emails.
This is the script code:
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet to send emails');
const data = sh.getRange('A2:G'+sh.getLastRow()).getValues();
data.forEach(r=>{
let overdueValue = r[0];
if (overdueValue === ""){
let name = r[6];
let message = 'Text ' + name;
let subject = 'TEXT.'
MailApp.sendEmail('myemail#gmail.com', subject, message);
}
});
}
And this is the link to the test sheet:
https://docs.google.com/spreadsheets/d/1OKQlm0PjEjDB7PXvt34Og2fa4vPZWnvLazTEawEtOXg/edit?usp=sharing
In this test case, I "should" only get one email, related to ID 55555. With the script as is, I get one related to 55555 and several others "undefined".
To avoid e-mail spam, I didn't add the script to that sheet but it shows the "Vlookup" idea.
Can anyone give me a hand, please?
Thank you in advance
Issue:
The issue with your original script is that the sh.getLastRow returns 1000 (it also processes those rows that doesn't have contents, result to undefined)
Fix 1: Get specific last row of column G:
const gValues = sh.getRange('G1:G').getValues();
const gLastRow = gValues.filter(String).length;
or
Fix 2: Filter data
const data = sh.getRange('A2:G' + sh.getLastRow()).getValues().filter(r => r[6]);
Note:
As Kris mentioned in the comments, there is a specific case where getting the last row above will fail (same with getNextDataCell). This will not properly get the last row WHEN there are blank rows in between the first and last row of the column. If you have this kind of data, then use the 2nd method which is filtering the data.
If your data in column G does not have blank cells in between the first and last row, then any method should work.
I checked your test sheet, and sh.getLastRow() is 1000.
OPTION 1
If column G won't have empty cells between filled ones, then you can do this:
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName("Sheet to send emails");
// get the first cell in column G
var gHeader = sheet.getRange(1, 7);
// equivelent of using CTRL + down arrow to find the last da
var lastRow = gcell.getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
const data = sheet.getRange(2, 1, lastRow, 7).getValues();
OPTION 2
Add another condition to your code - like this:
data.forEach(r=>{
let overdueValue = r[0];
let name = r[6]
// check if the value in col A is blankd and col G is not blank
if (overdueValue === "" && name !== ""){
let message = 'Text ' + name;
let subject = 'TEXT.'
MailApp.sendEmail('myemail#gmail.com', subject, message);
}
});
And to speed it up, use a named range to limit how many rows it has to iterate through:
const ss = SpreadsheetApp.getActive();
const data = ss.getRangeByName("Your_NamedRange_Here").getValues();

Get Row and Column number from "ThisComponent.CurrentSelection" in libreoffice calc basic

I have this code where I can get which one is the current selected cell and use it to modify its value:
theSelection = ThisComponent.CurrentSelection
theSelection.setString("some value")
Now I want to move to the next column to the right, if it was Microsoft excel VBA I could just use something like theSelection.Offset(0,1) but that's not the case. So I'm doing some workarounds of course:
nextCell = oActiveSheet.getCellByPosition( ???currentColumn + 1, ???currentRow)
ThisComponent.CurrentController.select( nextCell )
I just want to know the simplest way to replace these ??? to the actual values of the theSelection var to move to the next column to the right.
I also tried this:
nextCell = oActiveSheet.getCellByPosition( column() + 1, row())
But I don't know why it is always returning column() = 1 and row() = 1 in regardless of which is the value of the CurrentSelection. Thanks in advance for the help.
Get the cell address.
Sub ChangeAndThenGoToCellToRightOfSelection
oActiveSheet = ThisComponent.getCurrentController().getActiveSheet()
oSels = ThisComponent.getCurrentSelection()
If oSels.supportsService("com.sun.star.sheet.SheetCell") Then
'A single cell is selected.
oSels.setString("some value")
address = oSels.getCellAddress()
nextCell = oActiveSheet.getCellByPosition(address.Column + 1, address.Row)
ThisComponent.CurrentController.select(nextCell)
End If
End Sub
To see what an object can do, use an introspection tool such as XrayTool or MRI.

Script is taking 11 - 20 seconds to lookup up an item in an 18,000 row data set

I have two Google sheets workbooks.
One is the "master" source of lookup data with a key based on manufacturer item #, which could be anything from 1234 to A-01/234-Name_1. This sheet, referenced via SpreadsheetApp.openByUrl, has 18,000 rows and 13 columns. The key column has been converted to plain text and the sheet is sorted by this column.
The second is the "template" where people enter item #s that they need to look up against the master, typically 20 - 1500 items at a time.
The script is in the template. It is very slow and routinely times out after 30 minutes. It was written by someone else and I am new to App Script, but I think I've managed to understand what the script is doing and where the bottleneck is occurring.
It does a bunch of stuff, but this is the meat of the lookup:
var numrows = master.getDataRange().getNumRows();
var masterdata = master.getDataRange().getValues();
var itemnumberlist = template.getDataRange().getValues();
var retreiveddata = [];
// iterate through the manf item number list to find all matches in the
// master and return those matches to another sheet
for (i = 1; i < template.getDataRange().getValues().length; i++) {
for (j = 0; j < numrows; j++) {
if (masterdata[j][1].toString() === itemnumberlist[i][1].toString()) {
retreiveddata.push(data[j]);
anothersheet.appendRow(data[j]);
}
}
}
I used Logger.log() to determine that each time through the i loop is taking 11 - 19 seconds, which just seems insane.
I've been doing some google searching and I've tried a couple of different things...
First I tried moving the writing of found data out of the for loop so the script would be doing all of its reading first and then writing in one big chunk, but I couldn't get it exactly right. My two attempts are below.
var mycounter = 0;
for (i = 0; i < template.getDataRange().getValues().length; i++) {
for (j = 0; j < numrows; j++) {
if (masterdata[j][0].toString() === itemnumberlist[i][0].toString()) {
retreiveddata.push(masterdata[j]);
mycounter = mycounter + 1;
}
}
}
// Attempt 1
// var myrange = retreiveddata.length;
// for(k = 0; k < myrange; k++) {
// anothersheet.appendRow(retreiveddata.pop([k]);
// }
//Attempt 2
var myotherrange = anothersheet.getRange(2,1,myothercounter, 13)
myotherrange.setValues(retreiveddata);
I can't remember for sure, because this was on Friday, but I think both attempts resulted in the script trying to write the entire master file into "anothersheet".
So I temporarily set this aside and decided to try something else. I was trying to recreate the issue in a couple of sample spreadsheets, but I was unable to do so. The same script is getting through my 15,000 row sample "master" file in less than 1 second per lookup. The only thing I can think of is that I used a random number as my key instead of a weird text string.
That led me to think that maybe I could use a hash algorithm on both the master data and the values to be looked up, but this is presenting a whole other set of issues.
I borrowed these functions from another forum post:
function GetMD5Hash(value) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5,
value);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
Utilities.sleep(100);
}
return txtHash;
}
function RangeGetMD5Hash(input) {
if (input.map) { // Test whether input is an array.
return input.map(GetMD5Hash); // Recurse over array if so.
Utilities.sleep(100);
} else {
return GetMD5Hash(input)
}
}
It literally took me all day to get the hash value for all 18,000 item #s in my master spreadsheet. Neither GetMD5Hash nor RangeGetMD5Hash will return a value consistently. I can only do a few rows at a time. Sometimes I get "Loading..." indefinitely. Sometimes I get "#Name" with a message about GetMD5Hash being undefined (despite the fact that it worked on the previous row). And sometimes I get "#Error" with a message about an internal error.
This method actually reduces the lookup time of each item to 2 - 3 seconds (much better, but not great). However, I can't get the hash function to consistently work on the input data.
At this point I'm so frustrated and behind on my other work that I thought I'd reach out to the smart people on these forums and hope for some sort of miracle response.
To summarize, I'm looking for suggestions on these three items:
What am I doing wrong in my attempt to move the write out of the for loop?
Is there a way to get my hash value faster or utilize a different method to accomplish the same goal?
What else can I try to help speed up the script?
Any suggestions you can offer would be greatly appreciated!
-Mandy
It sounds like you hit on the right approach with attempting to move the appendRow() call out of the loop. Anytime you are reading or writing to a spreadsheet you can expect the individual call to take 1 to 2 seconds, so this will eat up a lot of time when you get matches. Storing the matches in an array and writing them all at once is the way to go.
Another thing I notice is that your script calls getValues() in the actual for loop condition statement. The condition statement is executed each time on each iteration of the loop, so this is potentially wasting a lot of time even when you don't have matches.
A final tweak that may be helpful depending on your desired behaviour. You can stop the inner for loop after it finds the first match, which, if you only care about the first match or know there will only be one match, will save you a lot of iterations. To do this, put "break" immediately after the retreiveddata.push(masterdata[j]); line.
To fix the getValues issue, Change:
for (i = 1; i < template.getDataRange().getValues().length; i++) {
To:
for (i = 1; i < itemnumberlist.length; i++) {
And that fix along with the appendRow issue, and including the break call:
for (i = 1; i < itemnumberlist.length; i++) {
for (j = 0; j < numrows; j++) {
if (masterdata[j][0].toString() === itemnumberlist[i][0].toString()) {
retreiveddata.push(masterdata[j]);
break; //stop searching after first match, move on to next item
}
}
}
//make sure you have data to write before trying to write it.
if(retreiveddata.length > 0){
var myotherrange = anothersheet.getRange(2,1,retreiveddata.length, retreiveddata[0].length);
myotherrange.setValues(retreiveddata);
}
If you are re-using the same sheet for "anothersheet" on each execution, you may also want to call anothersheet.clear() to erase any existing data before you write your fresh results.
I would pass on the hashing approach altogether, comparing strings is comparing strings, so whether they are hashes or actual part numbers I wouldn't expect a significant difference.

How to automatically generate sequent numbers when using a form

Ahab stated in 2010: the complex looking number based on the Timestamp has one important property, the number can not change when rows are deleted or inserted.
As long as the submitted data is not changed by inserting deleting rows the simple formula =ArrayFormula(ROW(A2:A) - 1) may be the easiest one to use.
For other situations there is no nice reliable solution. :(
Now we live in 2015. Maybe times have changed?
I need a reliable way to number entries using a form.
Maybe a script can do the trick? A script that can add 1 to each entry?
That certain entry has to keep that number even when rows are deleted or inserted.
I created this simple spreadsheet in which I added 1,2, and 3 manually,please have a look:
https://docs.google.com/spreadsheets/d/1H9EXns8-7m9oLbCrTyIZhLKXk6TGxzWlO9pOvQSODYs/edit?usp=sharing
The script has to find the maximum of the former entries, which is 3, and then add 1 automatically.
Who can help me with this?
Grtz, Bij
Maybe a script can do the trick? A script that can add 1 to each
entry?
Yes, that would be what you need to resort to. I took the liberty of entering this in your example ss:
function onEdit(e) {
var watchColumns = [1, 2]; //when text is entered in any of these columns, auto-numbering will be triggered
var autoColumn = 3;
var headerRows = 1;
var watchSheet = "Form";
var range = e.range;
var sheet = range.getSheet();
if (e.value !== undefined && sheet.getName() == watchSheet) {
if (watchColumns.indexOf(range.getColumn()) > -1) {
var row = range.getRow();
if (row > headerRows) {
var autoCell = sheet.getRange(row, autoColumn);
if (!autoCell.getValue()) {
var data = sheet.getDataRange().getValues();
var temp = 1;
for (var i = headerRows, length = data.length; i < length; i++)
if (data[i][autoColumn - 1] > temp)
temp = data[i][autoColumn - 1];
autoCell.setValue(temp + 1);
}
}
}
}
}
For me the best way is to create a query in a second sheet pulling everything from form responses in to second column and so on. then use the first column for numbering.
In your second sheet B1 you would use:
=QUERY(Form!1:1004)
In your second sheet A2 you would use:
=ARRAYFORMULA(if(B2:B="",,Row(B2:B)-1))
I made a second sheet in your example spreadsheet, have a look at it.

jquery add numbers within one input field

I have found ways to add the numbers of multiple input fields together and output the result. However I am trying to find a way to add numbers within one field, if possible. I basically want it to work as if it was an excel cell and add up numbers using a + in between each one.
So as the user enters =125+11+110 it automatically is adding those numbers to and displaying the total next to the box.
You can split the string:
var expression = "125+11+110";
var operands = expression.split("+");
var sum = 0;
for (var i = 0; i < operands.length; i++) {
sum += parseInt(operands[i]); // use parseFloat if you use decimals as well.
}
But the above example will not know hot to do multiple types of operations in single text box. For example, 100+76-45 will give you incorrect answer.
You can also use eval, but know that it can be harmful if you used it in a wrong way.
var expression = "125+11+110";
var sum = eval(expression);
If you use eval:
do not store the strings user submitted in the database without sanitation.
do not send back the strings user submitted to the browser as JavaScript.
to be safe, just do not even send the user's strings to server at all.
This is the dirty method. It splits the input between the plus signs and adds up the values in the array:
var userinput = "125+11+110";
var userinputarray = userinput.split("+");
var totalamount = 0;
$(userinputarray).each(function(key,value){
totalamount += parseFloat(value);
})
It does not handle subtraction. However you can do a regex match instead:
var userinput = "125+11+110";
var userinputarray = userinput.match(/(\+|\-){0,1}[0-9.]{1,}/g);
var totalamount = 0;
$(userinputarray).each(function(key,value){
totalamount += parseFloat(value);
});
Parsefloat will remove the + symbol, while still using the negative sign.
var data = $('#inputfeildID').text();
var arr = data.split('+');
var total = 0;
for(i=0; i < arr.length ; i ++){
total += arr[i];
}
console.log( total );
When user click enter or submit , first get the value or text in the input field & then split it from + , then add the array elements . you will get the total value of the input box ..
if you want to add those number automatically when user is typing , you have to use jQuery keyup function & when user press + , then add the next number to previous one
You can put a keyup listener on the text box. Then in the code fired by the listener, if "myinput" is the id of your input field:
var exp = document.getElementById('myinput').value;
var result = eval(exp);
"result" will be the value of the expression. You should also really check "exp" to see that it is a valid entry, because the user could put any kind of garbage into the input field, and there could also be security issues.
You should use eval. Like so...
var input = "125+11+110";
var answer = eval(input);
http://www.w3schools.com/jsref/jsref_eval.asp