You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI- - javascript

I intend to run my script on Google sheet
What I'm doing is to restore the values ​​of the cells, and use an if statement to compare an identifier cell with another userid cell.
If they are different, I want to eliminate that entire row, if they are equal I want to leaving the entire row as it is.
I get the error:
You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI-
My code:
function myFunction() {
function Lento() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var rows = sheet.getDataRange();
var values = rows.getValues();
var numCols = rows.getNumColumns();
var numRows = rows.getNumRows();
for (var r=1; r<values.length; r++) {
var row = values[r],
identificador = row[0],
palabraclave = row[1],
ciudad = row[2],
fecha = row[4],
pais = row[5],
idusuario = row[6],
nombre = row[7],
email = row[8],
telefono = row[9],
mensaje = row[10],
urllanding = row[11],
fechausuario = row[12];
Logger.log(identificador);
Logger.log(palabraclave);
Logger.log(ciudad);
Logger.log(fecha);
Logger.log(pais);
}
if (row[0] !== row[6]) {
spreadsheet.deleteRow(row);
}
}
Lento();
}

I think your problem is with spreadsheet.deleteRow(row). First, you want to delete the row on this particular sheet, so it should be sheet.deleteRow(...). The other problem is that deleteRow expects an integer as an argument, but you've provided row, which is an array. To delete the row, you want to do
sheet.deleteRow(r+1);
because r is the integer linked to the position in the array, not row. See the documentation on deleteRow(rowPosition):
https://developers.google.com/apps-script/reference/spreadsheet/sheet#deleterowrowposition

Now I have the solution to what I do.
as well as it gives errors since the comprovación of the array is null therefore not work , the code would look like .
function myFunction() {
function Lento() {
var h1 = SpreadsheetApp.getActive().getSheetByName('Hoja 1');
var h2 = SpreadsheetApp.getActive().getSheetByName('Hoja 2');
var rowsh1 = h1.getDataRange();
var valuesh1 = rowsh1.getValues();
var numColsh1 = rowsh1.getNumColumns();
var numRowsh1 = rowsh1.getNumRows();
var rowsh2 = h2.getDataRange();
var valuesh2 = rowsh2.getValues();
var numColsh2 = rowsh2.getNumColumns();
var numRowsh2 = rowsh2.getNumRows();
var idusuario = [];
var identificador = [];
//recorremos fila a fila y cogemos los datos de la hoja1
for (var r = 1; r < valuesh2.length; r++) {
var rowh2 = valuesh2[r],
nombre = rowh2[1],
email = rowh2[2],
telefono = rowh2[3],
mensaje = rowh2[4],
urllanding = rowh2[5],
fechausuario = rowh2[6];
idusuario[r] = rowh2[0]; //Guardamos los gclid del usuario en un array
}
//recorremos fila a fila y cogemos los datos de la hoja2
for (var r = 1; r < valuesh1.length; r++) {
var rowh1 = valuesh1[r],
palabraclave = rowh1[1],
ciudad = rowh1[2],
fecha = rowh1[4],
pais = rowh1[5];
identificador[r] = rowh1[0]; //Guardamos los gclid en un array
}
for (var i = identificador.length - 1; i >= 0; i--) {
var encontrado = false;
for (var y = 1; y < idusuario.length; y++) {
if (identificador[i] == null || idusuario[y] == null) continue;
if (identificador[i] == idusuario[y]) {
encontrado = true;
break;
}
}
if (!encontrado) {
h1.deleteRow(i + 1);
}
}
}
Lento();
}

Related

How can I get all data in a unique message, from a sheet A from comparing two cells in different spreadsheet

I want to compare two cells in sheetA and SheetB like in the screens below to get the exact results (screen).
I've run a code, but it sends me multiple messages (Each single data row in a message) instead of a single message containing all the information (See results screen).
SheetA
SheetB
Results
Thank you in advance.
Here's the code I used :
function myFunction(){
var SheetA = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetA');
var SheetB = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetB');
var lr = SheetA.getLastRow();
for (i = 2; i < lr+1; i++){
var StoreB = SheetB.getRange(i,1).getValue();
var StoreA = SheetA.getRange(2,2).getValue();
var Activity = SheetA.getRange(2,4).getValue();
if (StoreA == StoreB && Activity == 'Actif'){
var order = SheetB.getRange(i,2).getValue();
var date_li = SheetB.getRange(i,4).getValue();
var date = Utilities.formatDate(new Date(date_li), 'Europe/Paris', 'dd/MM/yyyy');
var ref = SheetB.getRange(i,5).getValue();
var desi = SheetB.getRange(i,6).getValue();
var quantity = SheetB.getRange(i,7).getValue();
var livred = SheetB.getRange(i,8).getValue();
var email = SheetA.getRange(2,5).getValue();
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.email = email;
htmlTemplate.order = order;
htmlTemplate.date = date;
htmlTemplate.desi = desi;
htmlTemplate.ref = ref;
htmlTemplate.quantity = quantity;
htmlTemplate.livred = livred;
const htmlforEmail = htmlTemplate.evaluate().getContent();
console.log(htmlforEmail)
MailApp.sendEmail(
email,
'Modification date d\'inventaire',
"SVP Ouvrez ce mail avec le support HTML",
{htmlBody: htmlforEmail}
);
}
}
}
This is how I would do it but it will necessitate having to change the template so that it can handle a 2d array to place the data in to a table. Fortunately, the data also includes the first row of headers for the table.
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sha = ss.getSheetByName('SheetA');//reference
const shb = ss.getSheetByName('SheetB');//order data
const hA = shb.getRange(1,1,1,8).getDisplayValues().flat().splice(2,1);
const vsb = shb.getRange(2, 1, shb.getLastRow() - 1, shb.getLastColumn()).getDisplayValues();
const StoreA = sha.getRange(2, 2).getValue();
const Activity = sha.getRange(2, 4).getValue();
const email = sha.getRange(2, 5).getValue();
const del = { pA: [] };
if (Activity == 'Actif') {
vsb.forEach((r, i) => {
let [st, order, , date_li, date, desi, quantity, livred] = r
if (StoreA == st) {
if (!del.hasOwnProperty(st)) {
del[st] = [];
del[st] = hA;//puts the titles into the data
del[st].push([r[0], r[1], r[3], r[4], r[5], r[6], r[7]]);
del.pA.push(st);
} else {
del[st].push([r[0], r[1], r[3], r[4], r[5], r[6], r[7]]);
}
}
});
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.order = del[st];
}
MailApp.sendEmail(email, 'Modification date d\'inventaire', "SVP Ouvrez ce mail avec le support HTML", { htmlBody: htmlTemplate.evaluate().getContent() });
}
Try this
function myFunction(){
var SheetA = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetA');
var SheetB = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetB');
var lr = SheetA.getLastRow();
var order = "";
var date_li = ""
var date = "";
var ref = "";
var desi = "";
var quantity = "";
var livred = "";
var email = "";
for (i = 2; i < lr+1; i++){
var StoreB = SheetB.getRange(i,1).getValue();
var StoreA = SheetA.getRange(2,2).getValue();
var Activity = SheetA.getRange(2,4).getValue();
if (StoreA == StoreB && Activity == 'Actif'){
order += SheetB.getRange(i,2).getValue()+'\n';
date_li += SheetB.getRange(i,4).getValue()+'n';
date += Utilities.formatDate(new Date(date_li), 'Europe/Paris', 'dd/MM/yyyy')+'\n';
ref += SheetB.getRange(i,5).getValue()+'\n';
desi += SheetB.getRange(i,6).getValue()+'\n';
quantity += (+SheetB.getRange(i,7).getValue());
livred = SheetB.getRange(i,8).getValue();
email = SheetA.getRange(2,5).getValue();
}
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.email = email;
htmlTemplate.order = order;
htmlTemplate.date = date;
htmlTemplate.desi = desi;
htmlTemplate.ref = ref;
htmlTemplate.quantity = quantity;
htmlTemplate.livred = livred;
const htmlforEmail = htmlTemplate.evaluate().getContent();
console.log(htmlforEmail)
MailApp.sendEmail(
email,
'Modification date d\'inventaire',
"SVP Ouvrez ce mail avec le support HTML",
{htmlBody: htmlforEmail}
);
}
}
````

How to print data from an object and error [object Object] does not appear?

I have this program that as soon as it starts up, it asks you to enter the number of books that you want to register in the program and the number of authors that each book will have.
The program will ask you to register a name for each author, surname, age and nationality.
Once this is done, there is a button that shows all the books registered with their authors and the data of the books, and I have the problem that I am not able to show the data of the authors since only [object Object] appears.
Edit:
I have managed to print the element.autores by console.log, without the error obejct object appearing but I am not able to get it out through a document.write or something similar, here I leave a screenshot of how it should appear:
And if I try to put elements.autores.nombre to print only the name, it appears undefined both in the console.log and in the document.write
Here my code:
javascript:
var biblioteca = new Array();
function libro(titulo, autores, anyo, editorial) {
this.titulo = titulo;
this.autores = autores;
this.anyo = anyo;
this.editorial = editorial;
}
function autor(nombre, apellidos, edad, nacionalidad) {
this.nombre = nombre;
this.aepellidos = apellidos;
this.edad = edad;
this.nacionalidad = nacionalidad;
}
window.onload = function () {
document.getElementById("mostrar").onclick = Mostrar;
document.getElementById("insertar").onclick = insertarlibro;
document.getElementById("insertar").onclick = insertarautor;
}
function insertarlibro() {
var autores = new Array();
var titulo = prompt("Insertar el nombre del titulo del libro");
var anyo = parseInt(prompt("Año"));
var editorial = prompt("Inserta su editorial");
var numautores = parseInt(prompt("Cuantos autores vas a insertar"));
for (let i = 0; i < numautores; i++) {
let autor = insertarautor();
autores.push(autor);
}
var registrohecho = new libro(titulo, autores, anyo, editorial);
return registrohecho;
}
console.log(insertarlibro);
function insertarautor() {
var nombre = prompt("Insertar el nombre del autor").toUpperCase();
var apellidos = prompt("Insertar el apellidos del autor").toUpperCase();
var edad = parseInt(prompt("Edad"));
var nacionalidad = prompt("¿De que pais es el autor?");
var registrohecho = new autor(nombre, apellidos, edad, nacionalidad);
return registrohecho;
}
console.log(insertarautor);
var numlibros = parseInt(prompt("Cuantos libros vas a insertar"));
for (let i = 0; i < numlibros; i++) {
var insertalibro = insertarlibro();
biblioteca.push(insertalibro);
}
function Mostrar() {
biblioteca.forEach(element => {
console.log("Error" + JSON.stringify(element.autores));
var muestra = "Nombre del libro:" + element.titulo + " autores: " + element.autores + " Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
}
And the html part:
<div id="insertar">
<input type="button" value="Insertar">
</div>
<div id="mostrar">
<input type="button" value="Mostrar">
</div>
You are trying to get element.autores, which is an array. To get e.g. get the nombre, you wold have to acces it with element.autores[0].nombre.
So your code to output all books (with authors) would be something like this:
biblioteca.forEach(element => {
var muestra = "Nombre del libro:" + element.titulo + " autores: ";
element.autores.forEach(author => {
muestra += `nombre: ${author.nombre}, aepellidos: ${author.aepellidos}, edad: ${author.edad}, nacionalidad: ${author.nacionalidad} `;
})
muestra += "Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});

Classroom API IndividualStudentsOptions in Google Apps Script

Is it possible to use IndividualStudentsOptions object from Google Apps Script? I'm trying to create the object but returns this error
GoogleJsonResponseException: No se ha podido llamar a la API classroom.courses.courseWork.create; error: Invalid JSON payload received. Unknown name "individualStudentsOptions" at 'course_work': Proto field is not repeating, cannot start list.
It seems that is not possible from GAS.
function enviarclassdos(datos,alumnos){
// datos: object with needed variables for classroom publishing
// alumnos: individual students (array [students])
var stdid = []; //Array of IDs of individual students
//Getting the IDs of the individual students
var hojacuentas = SpreadsheetApp.openById("1oHlpSyRB913LWpj-UNTKattO").getSheetByName("CUENTAS");
var datacuentas = hojacuentas.getDataRange().getValues();
for(var al =0; al<alumnos.length; al++){
var alum = alumnos[al][0];
for (var dt=0; dt<datacuentas.length; dt++){
var alumdt = datacuentas[dt][0];
if (alumdt == alum){
var cuenta = datacuentas[dt][3];
stdid.push(cuenta);}}}
var curso = datos.curso;
var tipo = datos.tipo;
if (curso == "Primero A"){var id = "14085771****";}
if (curso == "Primero B"){var id = "14085996****";}
if (curso == "Segundo A"){var id = "14085996****";}
if (curso == "Segundo B"){var id = "14085996****";}
if (curso == "Cuarto AB"){var id = "14085996****";}
var titulo = datos.concepto;
var descripcion = datos.descripcion;
var fecha = datos.fecha;
var tema = datos.tipo
var ClassSource =
{
title: titulo,
description: descripcion,
state: "PUBLISHED",
workType: "ASSIGNMENT",
topicId: tema,
maxPoints: 100,
assigneeMode: "INDIVIDUAL_STUDENTS"
}
//This is the object that produces the error message
ClassSource.individualStudentsOptions = {studentIds:stdid};
var clss = Classroom.Courses.CourseWork;
var wrk = clss.create(ClassSource, id);
}
Instead of
ClassSource.individualStudentsOptions = [{studentIds:stdid}];
use
ClassSource.individualStudentsOptions = {studentIds:[stdid]};
Reference
https://developers.google.com/classroom/reference/rest/v1/IndividualStudentsOptions

Array clears after assignment "Array have Select values"

I create an array 'userSelects' with 'select's from an 'option' array, the 'option' array is created with my usernamesunits array.
If I start the function at the first time, it works, but the elements are removed from my array.
running MySQL 5 with php7.3, I use a local server and a webspace.
// Main Tet
let testSelect = document.createElement("select");
let testOption = document.createElement("option");
testSelect.id = "1";
testOption.text = "alle";
testSelect.add(testOption);
let name = document.createElement("select");
let nameOption = document.createElement("option");
let n1ameOption = document.createElement("option");
name.id = "2";
nameOption.text = "--none--";
name.add(nameOption);
nameOption = document.createElement("option");
nameOption.text = userSafe[0].name;
name.add(nameOption);
n1ameOption.text = userSafe[1].name;
name.add(n1ameOption);
document.body.appendChild(name);
document.body.appendChild(testSelect);
// onchange womit die user id übergeben wird
//
name.addEventListener("change",function(){
console.log("tabe :" + name.value);
test(name.selectedIndex - 1 ,testSelect.id);
});
function test(id,oldID){
// r is a new test select
r = document.getElementById(oldID);
r.length = 0;
var sicherheitsCopy = userSelects;
sicherheitsCopy = userSelects;
// wen option select hinzugefügt wird, wird es gelöscht von der userSelect[index]
for(let index = 0; sicherheitsCopy[id].length != 0; index){
r.add(sicherheitsCopy[id][0])
console.log("index nummer " + sicherheitsCopy[id].length);
}
}
// generate userSelects
function initUnitSelect(){
for(let index = 0; index < userSafe.length; ++index){
let testSelect = document.createElement("select");
let userOptionFirstUnit = document.createElement("option");
userOptionFirstUnit.text = "--none--";
testSelect.add(userOptionFirstUnit);
for(let index2 = 0; index2 < userUnitsCase[index][0].length; ++index2){
let userOption = document.createElement("option");
userOption.text = userUnitsCase[index][0][index2];
testSelect.add(userOption);
}
userSelects[index] = testSelect;
console.log("userSelects " + userSelects );
}
}
for an example, my test subdomain
https://twliste.deutschritter.eu/offiziersliste/
the first button show what I mean.
//edit i forget to post a code
// Global Variable
var sfgID = "sfg";
var counter = 0; // count fot hte sfgID
var supCounter = 0; // count for the supID
var supZeilenCounter = 0; // count the row in the table for the user unit
var testCounter = 0;
var sfgSupGroup = 5; //sup Tables
var sfgSupMembergroupe = 5; //Table rows
// Global URL
var getUserInformationURL = "https://twliste.deutschritter.eu/offiziersliste/php_interface/get_user_info.php";
var userSafe = []; // save all user with user informations
var userUnitsCase = []; // save all userUnits,
var userSelects = []; // save userSelects Index == userSafe Array Index

How to reduce execution time of this script (Google app script timeout)

I have this piece of script.
It filter a range by a criteria,
then It copy values that respect criteria in a specific sheet
then It deletes all the row in the original sheet that respect the criteria.
So that If my range contains more than 1000 rows, It's said to me error: Google app script timeout.
I put my code here, can You help me to get a better performance about execution time of this script?
function trasferisciDati() {
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Inserisci il mese dei dati da esportare', '(Esempio: agosto (tutto minuscolo))', ui.ButtonSet.OK_CANCEL);
var inizioTRASFERISCIVALORI = Utilities.formatDate(new Date(), "CET", "HH:mm:ss.SSS");
if (response.getSelectedButton() == ui.Button.OK) {
//get filtered range and set values to the new range
var description = ui.prompt('Inserisci una descrizione per questa esportazione', 'apparirà come tag dell\'esportrazione', ui.ButtonSet.OK_CANCEL);
var sourceData = SpreadsheetApp.openById("1XkYhjdQfgU7mVCR7E8mfZsf292I-cJ16PnpCimnd1v8").getSheetByName("Prova");
var destinationData = SpreadsheetApp.openById("1cdXMqqBwgWK5nCQUtAP_TyIIDOHksS7wWvSG4jRu658").getSheetByName("Prova");
var lastRow = sourceData.getLastRow();
var data = sourceData.getRange(1, 1, lastRow, 1).getValues();
var chiave = response.getResponseText();
for(var i=0;i<data.length;i++)
{
if (data[i][0] == chiave) {
var filteredRow = sourceData.getRange(i+1,1,1,5).getValues();
destinationData.appendRow(filteredRow[0]);
}
}
//number of records of the filtered range
var lastRow = destinationData.getLastRow();
var data = destinationData.getRange(1, 6, lastRow, 1).getValues();
var loop = 0
for(var i=0;i<data.length;i++)
{
if(!data[i][0])
{
var loop = loop + 1
}
}
Logger.log(Utilities.formatString('%1.0f', Math.floor(loop)))
//appendi timestamp al rigo ed eventuale descrizione aggiuntiva inserita dall'utente
var lastRow = destinationData.getLastRow();
var data = destinationData.getRange(1, 6, lastRow, 1).getValues();
var timestamp = Utilities.formatDate(new Date(), "CET", "dd/MM/YYYY HH.mm.ss")
for(var i=0;i<data.length;i++)
{
if(!data[i][0])
{
destinationData.getRange(i+1,6).setValue(timestamp)
destinationData.getRange(i+1,7).setValue(description.getResponseText())
}
}
//cancella l'intervallo originale
var maxRows = sourceData.getMaxRows();
var data = sourceData.getRange(1, 1, maxRows, 1).getValues();
for(var i=data.length; i>=0;i--)
{
if (data[i] == chiave) {
sourceData.deleteRow(i+1)
}
}
var fineTRASFERISCIVALORI = Utilities.formatDate(new Date(), "CET", "HH:mm:ss.SSS");
var inTime=inizioTRASFERISCIVALORI.split(":");
var outTime= fineTRASFERISCIVALORI.split(":");
var hr = outTime[0] - inTime[0];
var min = ((outTime[1] - inTime[1])+hr*60)%60;
var sec = ((outTime[2] - inTime[2])+min*60)%60;
var duration = Utilities.formatString('%2.0f', Math.floor(hr)) + 'h ' + Utilities.formatString('%2.0f', Math.floor(min)) + 'm ' + Utilities.formatString('%2.0f', sec) + 's';
ui.alert('Trasferite '+ Utilities.formatString('%1.0f', Math.floor(loop)) +' righe in '+ duration, ui.ButtonSet.OK)
} else if (response.getSelectedButton() == ui.Button.CANCEL) {
SpreadsheetApp.getUi().alert('L\'utente ha annullato l\'operazione');
} else {
SpreadsheetApp.getUi().alert('L\'utente ha chiuso la finestra di dialogo');
}
}
You might try this:
var data = sourceData.getRange(1, 1, lastRow, 5).getValues();
var chiave = response.getResponseText();
for(var i=0;i<data.length;i++)
{
if (data[i][0] == chiave)
{
//var filteredRow = sourceData.getRange(i+1,1,1,5).getValues();
destinationData.appendRow(data[i]);
}
}
And you might consider the same thing on your destination data.

Categories