Loop opening a spreadsheet, and copying from sheet a to sheet b - javascript

I just don't understand where the problem is,
must be super simple but this does not work.
Sorry for the newbee question.
function GoGetData() {
var ss =
SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = ss.getSheetByName('List des dossiers du Folder') // Sheet=liste des dossiers
for(var i=1; i>3; i++)
{
Logger.log(i);
var IdShpread = sheet.getRange(i,2,1,1); // va prender l,adresse de La sheet
var source = SpreadsheetApp.openById(IdShpread); // open la sheet avec les data
var sourcesheet = source.getSheetByName('regroup');
var targetsheet = source.getSheetByName('worksheet');
// Copy de l'ensemble de la Sheet
var rangeValues = sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
//pour copier seulement certaines parties a netraliser apres
//var rangeValues = sourcesheet.getRange("D7:K7").copyTo(targetsheet.getRange("D7:K7"), {contentsOnly: true});
}
}

To retrieve the sheet Ids, which are located in the cells of your range, you need to use the method getValue(). Modify your script as following:
function GoGetData() {
var ss = SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
var sheet = ss.getSheetByName('List des dossiers du Folder') // Sheet=liste des dossiers
for(var i=1; i<=3; i++) {
var IdShpread = sheet.getRange(i,2,1,1).getValue(); // va prender l,adresse de La sheet
var source = SpreadsheetApp.openById(IdShpread); // open la sheet avec les data
var sourcesheet = source.getSheetByName('regroup');
var targetsheet = source.getSheetByName('worksheet');
sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
}
}

Try this:
function GoGetData() {
var ss=SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
var sh=ss.getSheetByName('List des dossiers du Folder');
for(var i=1;i<3;i++) {
Logger.log(i);
var IdShpread=sh.getRange(i,2,1,1);
var source=SpreadsheetApp.openById(IdShpread);
var sourcesheet=source.getSheetByName('regroup');
var targetsheet=source.getSheetByName('worksheet');
sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
}
}

Related

my update of the prototype "string" cannot be printed to with log

I dont get how I can remove a list of words from a string using this type of formalism:
string.my_function(parameter[])
text_val = "je vous appel concernant le truc rouge"
String.prototype.clean_string = function (stop_words) {
for (i = 0; i < stop_words.length; i++)
{
this.split(stop_words[i]).join('');
}
};
console.log(text_val.clean_string(['concernant','le']));
I have un undefined as a result and I don't get why.
I expect the result:
"je vous appel truc rouge"
I would use filter to strip the stop_words and then join the result:
text_val = "je vous appel concernant le truc rouge";
String.prototype.clean_string = function (stop_words) {
let splitted = this.split(' ');
for (i = 0; i < stop_words.length; i++) {
splitted = splitted.filter(w => w != stop_words[i]);
}
return splitted.join(' ');
};
console.log(text_val.clean_string(['concernant','le']));

All positions of the array are modified to the same value

I'm newbie programming in JavaScript and I have some problems with an array:
When I do a data exchange between an array and another position to position in a loop, all the positions of the array are converted to the same value. That is, the array positions are the same as the last added object.
I leave the code to help me to know what is happening:
.controller("UserAndEditLanguagePanel", function (usersFactory, userLanguagesFactory, LanguageFactory) {
var vm = this;
vm.userSesion = {};
var objAux = {};
objAux.langname = "";
objAux.level = "";
vm.lenguajesUsuario = new Array();
vm.funciones = {
cargarPerfil: function () {
usersFactory.obtenerUsuarioSesion().then(function (respuesta) {
vm.userSesion.idu = respuesta.idu;
vm.userSesion.username = respuesta.username;
vm.userSesion.email = respuesta.email;
console.log("Se han obtenido los datos de usuario de la sesión correctamente. Respuesta: ", respuesta);
userLanguagesFactory.obtenerLenguagesUsuarios().then(function (lenguajesUsuarios) {
console.log("Se han obtenidos los datos de los lenguajes de los usuarios. Respuesta: ", lenguajesUsuarios);
LanguageFactory.obtenerLenguajes().then(function (listaLenguajes) {
console.log("Se han traido los datos de los lenguajes. Respuesta: ", listaLenguajes);
console.log(lenguajesUsuarios);
for (var i = 0; i < lenguajesUsuarios.length; i++) {
if (lenguajesUsuarios[i].idu == vm.userSesion.idu) {
objAux.langname = listaLenguajes[lenguajesUsuarios[i].idl].langname;
objAux.level = lenguajesUsuarios[i].level;
vm.lenguajesUsuario.push(objAux);
}
}
Thank you very much in advance!
Need to initialise the object of objAux inside for loop and and dont crete and initialise the same object before the for loop it will work and fine.
.controller("UserAndEditLanguagePanel", function (usersFactory, userLanguagesFactory, LanguageFactory) {
var vm = this;
vm.userSesion = {};
//comment to below object creation and initialisation of object "objAux "
/*var objAux = {};
objAux.langname = "";
objAux.level = "";*/
vm.lenguajesUsuario = new Array();
vm.funciones = {
cargarPerfil: function () {
usersFactory.obtenerUsuarioSesion().then(function (respuesta) {
vm.userSesion.idu = respuesta.idu;
vm.userSesion.username = respuesta.username;
vm.userSesion.email = respuesta.email;
console.log("Se han obtenido los datos de usuario de la sesión correctamente. Respuesta: ", respuesta);
userLanguagesFactory.obtenerLenguagesUsuarios().then(function (lenguajesUsuarios) {
console.log("Se han obtenidos los datos de los lenguajes de los usuarios. Respuesta: ", lenguajesUsuarios);
LanguageFactory.obtenerLenguajes().then(function (listaLenguajes) {
console.log("Se han traido los datos de los lenguajes. Respuesta: ", listaLenguajes);
console.log(lenguajesUsuarios);
for (var i = 0; i < lenguajesUsuarios.length; i++) {
if (lenguajesUsuarios[i].idu == vm.userSesion.idu) {
var objAux = {
langname:'',
level:''
}
objAux.langname = listaLenguajes[lenguajesUsuarios[i].idl].langname;
objAux.level = lenguajesUsuarios[i].level;
vm.lenguajesUsuario.push(objAux);
}
}

You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI-

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();
}

add element JSON

I want to add new element to JSON ...
var estudiantes = [
{"Nombre":"Fernando","Codigo":"F50","Nota":100}
];
and this is the function to add the element, but doesnt works ...
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
/*agregar registro al JSON*/
var objeto = JSON.parse(estudiantes);
objeto.push('{"Nombre":"'+nombre+'","Codigo":"'+codigo+'","Nota":'+nota+'}');
estudiantes = JSON.stringify(objeto);
}
Your problem is that you aren't working with json, you are working with a javascript array of objects but trying to push json string instead of object into it
Try
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
// create new object
var objeto = {"Nombre":nombre,"Codigo":codigo,"Nota":nota};
//push object into array
estudiantes.push( objeto);
}
if you are working in js, you dont need work this like a string , you need work this with objects.
var linea= [];
var persona = new Object();
var objeto = new Object();
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
// create new object
persona.nombre=nombre;
persona.codigo=codigo;
persona.nota=nota;
linea.push(persona);
}
function generarjson(){
objeto.estudiantes=linea;
alert(JSON.stringify(objeto));
}
<button onclick="addEstudiantes();">Agregar estudiante</button>
<button onclick="generarjson();">Generar JSON</button>

zoom slider doesn't appears on my google map

First of all, I've also tried with Google Map APi zoom bar not showing, but with no success at all, so I'll tell you my problem. Ok, the code is as follows:
var datos = '<%=coorNom%>';
var origen='<%=origen%>';
var vAPIKey = '<%=APIKey%>';
var vLangmap = '<%=langmap%>';
var mapcoords;
$(document).ready(function() {
var script = document.createElement("script");
var gurl = "http://www.google.com/jsapi?callback=loadMapscoord&key=" + vAPIKey + "&oe=UTF8&ie=UTF8&hl=" + vLangmap;
script.src = gurl;
document.getElementsByTagName("head")[0].appendChild(script);
});
// Se utiliza esta función para no tener que cargar cada vez el api desde google maps y ya tenerlo descargado en el cliente
function loadMapscoord(){
setTimeout("google.load('maps', '2.x', {'callback':initMapcoord});", 100);
}
function initMapcoord(){
window.onunload=google.maps.Unload;
mapcoords = new google.maps.Map2(document.getElementById("mapa"));
mapcoords.enableDoubleClickZoom();
mapcoords.enableContinuousZoom();
mapcoords.enableScrollWheelZoom();
var mapControl = new google.maps.MapTypeControl();
mapcoords.addControl(mapControl);
var zoomControl = new google.maps.LargeMapControl();
mapcoords.addControl(zoomControl);
initializeCoords();
// Tenemos que esperar a cargar el mapa para ocultar la capa y mostrar la info.
if (origen == "info"){
parent.cuerpo(origen, 'localizacion');
}
}
function initializeCoords() {
mapcoords.clearOverlays();
mapcoords.closeInfoWindow();
mapcoords.setMapType(G_NORMAL_MAP);
mapcoords.setCenter(new google.maps.LatLng(0,0),0);
var bounds = new google.maps.LatLngBounds();
var markers = new Array(); //Array de marcadores
//Obtenemos la estructura de datos
var numcoords = datos.split('|');
for (var x = 0; x < numcoords.length-1; x++){
var coord = numcoords[x].split('#')[0];
var lat = coord.split('**')[0];
var lon = coord.split('**')[1];
if ((lat != undefined) && (lat != '') && (lon != undefined) && (lon != '')){
markers.push({latlng: new google.maps.LatLng( parseFloat( lat ), parseFloat( lon ) ), name: numcoords[x].split('#')[1]} );
}
}
//creamos los distintos marcadores y los asociamos al mapa
for (var z in markers){
marker = createMarker(markers[z]);
mapcoords.addOverlay(marker);
}
//Calculamos el centro y zoom adecuados para el mapcoords
for (var i in markers){
bounds.extend(markers[i].latlng);
}
mapcoords.setCenter(bounds.getCenter(), mapcoords.getBoundsZoomLevel(bounds) - 7);
if (origen == "imprimir"){
setTimeout("parent.imprime();",300);
}
}
</script>
The problem is that I've got the map, everything works fine, but I haven't got the zoom control slider, and I need it. You can see the line with var zoomControl = new google.maps.LargeMapControl();, and I understand it should work, and show the slider, but "au contrair", the two button, for zoom in and out, are together, with no slider between them.
Please..., can anybody tell me how to fix it? or what am I doing wrong?
Thanks a lot in advance.

Categories