Google Apps Script hangs while running a loop - javascript

I am using this code but I can't see anything in the logger. I can just see a message "Preparing for execution"
function testfunc() {
var s = SpreadsheetApp.getActiveSpreadsheet()
var sheet = s.getSheetByName("data")
var lastRow = sheet.getLastRow() - 1
var data = sheet.getRange(2,2,lastRow,5).getValues()
var fms = s.getSheetByName("FMS")
for (var i = 0;i < data.length; ++i){
var row = data[i]
var a = row[0]
var b = row[1]
var c = row[2]
var d = row[3]
var e = row[4]
Logger.log(i)
if (i = 1) {
Logger.log(i)
}
}
}
Where did I go wrong?
EDIT: As pointed out by #FedericoklezCulloca, I was missing an equal to sign in my if statement. The code should be :
function testfunc() {
var s = SpreadsheetApp.getActiveSpreadsheet()
var sheet = s.getSheetByName("data")
var lastRow = sheet.getLastRow() - 1
var data = sheet.getRange(2,2,lastRow,5).getValues()
var fms = s.getSheetByName("FMS")
for (var i = 0;i < data.length; ++i){
var row = data[i]
var a = row[0]
var b = row[1]
var c = row[2]
var d = row[3]
var e = row[4]
Logger.log(i)
if (i == 1) {
Logger.log(i)
}
}
}

Related

Delete Duplicate Data using Google Script

I am trying to make a script to automate deleting duplicate data based on column A. This is the current script I am using and it works.
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
sh.deleteRow((parseInt(i)+1) - d);
d++;
}
}
};
But this one is deleting the newly added row, what I want to achieve is it should delete the old duplicate row instead. How can I do that?
In else part instead of using i which represent your current row, use the indexOf the row you want to delete. Delete it first and then push the new one into array
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
let j = uA.indexOf(vA[i][hObj['key']]);
sh.deleteRow((parseInt(j)+1) - d);
d++;
uA.push(vA[i][hObj['key']]);
}
}
};

IF into a LOOP in GoogleScript about extracting emails

About extracting G-mails to a Google spreadsheet, how can I do to include an IF for dismissing specific e-mails by subject? For example: e-mails responses (with "RE:" in subject). I don't want these e-mails in my spreadsheet.
I've tried with a LOOP but it didn't work because LOOP keeps sending all e-mails to my spreadsheet without a previous selection.
Here's the code:
function GetEmails() {
var label = GmailApp.getUserLabelByName("MY LABEL");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
var from = message.getFrom()
var to = message.getTo();
var subject = message.getSubject();
var RE = subject.startsWith("RE:")
if ([RE != "RE:") {
process1(message);
} else {
process2(message)
}
}
}
function process1(message) {
var body = message.getPlainBody();
var subject = message.getSubject();
var date = message.getDate();
var from = message.getFrom();
var url = "GOOGLE SPREADSHEET"
var ss = SpreadsheetApp.openByUrl(url)
var sheet = ss.getActiveSheet();
sheet.appendRow([date, from, subject, body]);
}
function process2(message) {
var body = message.getPlainBody();
var subject = message.getSubject();
var date = message.getDate();
var from = message.getFrom();
var url = "GOOGLE SPREADSHEET"
var ss = SpreadsheetApp.openByUrl(url)
var sheet = ss.getActiveSheet();
sheet.appendRow([date, from, subject, body]);
}
}
RE is a boolean in your script.
Also DRY (Don't Repeat Yourself)
You likely meant to do
const url = "GOOGLE SPREADSHEET";
const ss = SpreadsheetApp.openByUrl(url);
const sheet = ss.getActiveSheet();
function process(message) {
var subject = message.getSubject();
if (subject.toUpperCase().startsWith("RE:")) {
return; // ignore RE
}
var body = message.getPlainBody();
var date = message.getDate();
var from = message.getFrom();
sheet.appendRow([date, from, subject, body]);
}
function GetEmails() {
var label = GmailApp.getUserLabelByName("MY LABEL");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
process(messages[j]);
}
}
}

Node Red multiple values to influxDB

i try with Node Red to build an query to send multiple values to an influxDB from a loop with this code:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var sendString = "";
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var actRegister = modbusStartRegister +i;
var actValue = inputArray[i];
if ( i >=1){
sendString = sendString + " ,"
}
sendString = sendString +"{register: " + actRegister +"," +"value: " + actValue +"}";
if ( i ==(lenInputArray-1)){
sendString = sendString + "]"
}
}
msg93.payload = sendString;
return msg93
But the insert in the influxDB is one line it looks at them interpreted as an complete string. How can I build or convert the string that the DB accept them as individual entry? Thanks for the help
This is because you are building a string, node an object.
You can build the array object on the fly like this:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var payload = [];
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var temp = {};
temp.register = modbusStartRegister +i;
temp.value = inputArray[i];
payload.push(temp);
}
msg93.payload = payload;
return msg93

Google sheets incorrect range width when no cmc matches

I am using this function to pull information from coinmarketcap using their v2 api. The problem I am getting is that if a "website_slug" does not exist on coinmarketcap, I get an incorrect range width error instead of the function just putting xxx in the cell. This can be recreated by having a cell in column B that doesn't match a website_slug on cmc (https://api.coinmarketcap.com/v2/ticker/).
function getMarketCap(sheetname) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
var assets = [];
var idRange = sheet.getRange("B1:B");
var lastRow = getLastRowOfRange(idRange);
var cellRange = sheet.getRange(1, 2, lastRow).getValues();
var mcRange = sheet.getRange(1, 3, lastRow);
var mcValues = [];
for (var i = 0; i < cellRange.length; i++) {
assets[i] = cellRange[i];
}
var req = [];
for (var i = 0; i < 16; i++) {
req.push({
muteHttpExceptions: true,
method: "get",
url: "https://api.coinmarketcap.com/v2/ticker/?start=" + (i * 100 + 1),
});
}
var responses = UrlFetchApp.fetchAll(req);
var res = responses.filter(function(e){return e.getResponseCode() == 200}).map(function(e){return JSON.parse(e.getContentText())});
if (responses.length != res.length) Logger.log("%s errors occurred.", responses.length - res.length);
var mcValues = [];
assets.forEach(function(e, h) {
mcValues[h] = []
res.some(function(f) {
Object.keys(f.data).some(function(g) {
if (f.data[g].website_slug == e[0]) {
mcValues[h][0] = f.data[g].quotes.USD.market_cap;
return true;
}
});
if (mcValues[h][0]) return true;
});
if (!mcValues[h][0]) mcValues[h][0] = 'xxx';
});
mcRange.setValues(mcValues);
}

javascript google script appendRow fails Service Error

I have a Google Apps Script that has been running for 3 months and starting a few weeks ago I'm getting a "Service Error" on the Appendrow function which I've bolded below. Any ideas on how to fix this?
function updateACOPS2(){
var ss = SpreadsheetApp.openById(".....")
var sheetSubmission = ss.getSheetByName("Sheet8");
var dataSubmission = sheetSubmission.getDataRange().getValues();
var lastColSubmission = sheetSubmission.getLastColumn();
var ssActive = SpreadsheetApp.openById("....")
var sheetActive = ssActive.getSheetByName("AcopsAll");
var sheetMain = ssActive.getSheetByName("Sheet1");
var dataActive = sheetActive.getDataRange().getValues();
var lastrow = sheetActive.getLastRow();
for(var i = 1; i < dataSubmission.length && dataSubmission[i][2] != ""; i++){
var currentIDSubmission = dataSubmission[i][2] + dataSubmission[i][3];
var checkGotMatch = false;
var toCopyRow = sheetSubmission.getRange(i+1,1,1,71);
// copy entire row for new record
Logger.log(currentIDSubmission);
// if there is a matching record flag as matched
for(var j = 1; j<dataActive.length; j++){
var currentIDActive = dataActive[j][2] + dataActive[j][3];
var currentIDSub = dataSubmission[i][2];
if(currentIDSub != '' && currentIDSubmission == currentIDActive){
checkGotMatch = true;
Logger.log(currentIDActive);
break;
}
}
// if it is a new record Append entire row
if(currentIDSub != '' && checkGotMatch == false){
**sheetMain.appendRow(toCopyRow.getValues()[0]);**
}
}
SpreadsheetApp.flush();
ss.toast("ACOPS Active has been updated.", "Complete");
}
In appendRow you need to pass an array so update your appendRow and try
sheetMain.appendRow([toCopyRow.getValues()[0]])

Categories

Resources