I'm trying to understand how I can remove a decimal. I have tried Math.trunc() but it never seems to remove. Logger.log(esValues.length) prints 500.0, I tried adding var removeDecimal = Math.trunc(esValues.length) then printing removeDecimal but I still get 500.0
var ss = SpreadsheetApp.getActiveSpreadsheet();
var es = ss.getSheetByName("School1");
var ms = ss.getSheetByName("School2");
var hs = ss.getSheetByName("School3");
var esValues = es.getDataRange().getValues();
var counterDell = 0;
var counterHP = 0;
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length); //This prints 500.0, Also tried adding here Logger.log(Math.trunc(esValues.length))
for (var i = 0; i < esValues.length; i++) {
var data = esValues[i];
var first = data[1];
var last = data[0];
var middle = data[2];
var studentid = data[3];
var device = data[4];
if (device.includes("Dell")) {
counterDell++;
} else if (device.includes("HP")) {
counterHP++;
}
}
Logger.log(`Dell count is ${counterDell}`)
Logger.log(`Hp count is ${counterHP}`)
}
Logger.log(esValues.length.split('.')[0])
breaks the decimal into integer and decimal portions, then we discard the decimal portion.
Actually just not using the logger will elimate the .0. For some stupid reason it has always done that.
function lfunko() {
var ss = SpreadsheetApp.getActive();
var es = ss.getSheetByName("School1");
var vs = es.getDataRange().getValues();
var counterDell = 0;
var counterHP =
for (var i = 0; i < vs.length; i++) {
var device = vs[4];
if (device.includes("Dell")) {
counterDell++;
} else if (device.includes("HP")) {
counterHP++;
}
}
const msg = `HP: ${counterHP} DELL: ${counterDell}`
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(msg),"Counts");
}
Related
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
var data = sheet.getDataRange().getValues();
var range = sheet.getRange("A1:L" + data.length);
range.sort(1);
const people = {};
for(var i = 0; i < data.length; i++) {
var name = data[i][0] + data[i][1];
console.log(i);
if (!people.name) {people.name = {rows: [i]};} else {people.name.rows.push(i)}
}
Logger.log(people);
}
What should I be doing differently? At the end, it logs {name={rows=[0.0, 1.0, 2.0, ...]}} instead of having an object for each name...?
In the sheet there's just a first name and last name on columns A and B, for around 80 rows.
Use the bracket syntax if you want to use dynamic names for properties: https://riptutorial.com/javascript/example/2321/dynamic---variable-property-names
In your case:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
var data = sheet.getDataRange().getValues();
var range = sheet.getRange("A1:L" + data.length);
range.sort(1);
const people = {};
for(var i = 0; i < data.length; i++) {
var name = data[i][0] + data[i][1];
console.log(i);
if (!people[name]) {people[name] = {rows: [i]};} else {people[name].rows.push(i)}
}
Logger.log(people);
}
i use the following code in Google Apps Script and i wanna get all messages in the inbox. This code gives "Cannot convert Array to number[][]. (line 19, file "Code")" error. How can i fix this code?
var myspreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var mysheet = myspreadsheet.getSheets()[0];
var start = 0;
var max = 19;
var count = 0;
while (count < 7) {
var threads = GmailApp.getInboxThreads(start, max);
var messages = GmailApp.getMessagesForThreads(threads);
//var froms = [];
messages.get
for (var i = 0; i < threads.length; i++) {
var thisThread = threads[i];
var messages = thisThread.getMessages();
var messageCount = thisThread.getMessageCount();
for ( var m = 0; m<=messageCount; m++) {
var lastMessage = messages[m];
froms = ([lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]);
mysheet.getRange(1, 1, froms.length, 7).setValues(froms);
froms = [];
}
}
start = start + 100;
count++;
}
}
Try changing this: froms = ([lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]);
to this: froms = ([[lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]]);
But really I think you have even bigger problems with your script.
I'd use something like this. But I can't test it very well because I don't keep a lot of junk in my inbox.
function emailsStuff() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheets()[0];
sh.clearContents();
var threads=GmailApp.getInboxThreads()
for(var i=0;i<threads.length;i++) {
var messages=GmailApp.getMessagesForThread(threads[i]);
for(var j=0;j<messages.length;j++) {
var msg=messages[j];
sh.appendRow([msg.getId(), msg.getSubject(), msg.getTo(), msg.getFrom(), msg.getCc(), JSON.stringify(msg.getDate()), msg.getReplyTo()]);
}
}
}
I'm currently developing a sheet that shows results from a set of data based on some filters but the data loads to slowly when getting the results, I've tried to follow the Best Practices from Google Documentacion with no luck, how can I set an array for the data to load faster?
Below is the code commented with what I've already tried
function realizarBusqueda() {
var inicio = SpreadsheetApp.getActive().getSheetByName("INICIO");
var aux_tags = SpreadsheetApp.getActive().getSheetByName("Aux_Tags");
var data = SpreadsheetApp.getActive().getSheetByName("Data");
var data_lc = data.getLastColumn();
var data_lr = data.getLastRow();
var searchRange = data.getRange(2,1, data_lr, data_lc);
var inicio_lc = inicio.getLastColumn();
inicio.getRange("A8:L1000").clearContent();
inicio.getRange("A8:L1000").clearFormat();
var countRows = inicio.getMaxRows();
inicio.deleteRows(20, (20-countRows)*-1);
if (inicio.getRange("B4").isBlank()) {
inicio.getRange("A8:L1000").clearContent();
inicio.getRange("A8:L1000").clearFormat();
var countRows = inicio.getMaxRows();
inicio.deleteRows(20, (20-countRows)*-1);
SpreadsheetApp.flush();
}
else if ((inicio.getRange("B4").getValue() != "" &&
inicio.getRange("C4").getValue() === "")) {
//filtrado 1
var arrayDatos = searchRange.getValues();
var inicio_fr = 8;
//var row = new Array(11);
for (var j = 2; j <= data_lr; j++) {
//row[j] = new Array(data_lr);
if (aux_tags.getRange("P2").getValue() === arrayDatos[j-2][4]) {
var inicio_fc = 1;
for (var i = 0; i < arrayDatos[j-2].length; i++) {
//row[j][i] = arrayDatos[j-2][i];
var row = arrayDatos[j-2][i];
inicio.getRange(inicio_fr, inicio_fc).setValue(row);
inicio_fc++;
}
inicio_fr++;
}
//inicio.getRange("A8").setValues(row);
}
}
I expect the output to load lots faster, currently what I've tried is commented, the code as-is is working but too slow
I just wanted to update this subject because I figured out myself, see attached the new code with the use of new 2D arrays
...
//filtrado 1
var arrayDatos = searchRange.getValues();
var inicio_fr = 8;
var rows = [];
var row = [];
for (var j = 2; j <= data_lr; j++) {
if (aux_tags.getRange("P2").getValue() === arrayDatos[j-2][4]) {
var inicio_fc = 1;
for (var i = 0; i < arrayDatos[j-2].length; i++) {
row.push(arrayDatos[j-2][i]);
if (i == 11) {
rows.push(row);
row = [];
}
}
}
}
inicio.getRange(8, 1, rows.length, rows[0].length).setValues(rows);
}
Now instead of writing on row at a time, I just write the whole array at once
I want to do a comparate a elementes inside of an array for get a specific value, how i could do it with this?
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 1; i < data.length; i++) {
dataToImport = {
Nivel:data[i][0],
Consumo:data[i][1],
Flujo:data[i][2],
if(dataToImport[Nivel]>99)
{
}
I'm not sure what your looking for but hopefully this will help.
function myfunction()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var data=sh.getDataRange().getValues();
var dataToImport = {};
for(var i=1;i<data.length;i++)
{
dataToImport = {'Nivel':data[i][0],'Consumo':data[i][1],'Flujo':data[i][2]}
if(dataToImport['Nivel']>99)
{
Logger.log('Nivel greater than 99 dataToImport = %s', dataToImport);
}
Logger.log(dataToImport);
}
}
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?