Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

318
Visualizações
¿Cómo puedo usar matrices para hacer este código más rápido?

Cuando hago clic en " Agregar elemento ", quiero que el código se ejecute y muestre la información en la tabla debajo del formulario.

 function AddItem() { //DEFINE ALL ACTIVE SHEETS` var ss = SpreadsheetApp.getActiveSpreadsheet(); //DEFINE MENU SHEET ` var poSheet = ss.getSheetByName("POF"); var itemSheet = ss.getSheetByName("Products"); `//GET NEXT ROW OF PO SHEET` var lastrowPO = poSheet.getLastRow() + 1; `//GET LAST ROW OF ITEM SHEET` var lastrowItem = itemSheet.getLastRow(); `// GET VALUE OF PART AND QUANTITY` var part = poSheet.getRange('B15').getValue(); var quantity = poSheet.getRange('B17').getValue(); ` // GET UNIT PRICE FROM ITEM SHEET` for (var i = 2; i <= lastrowItem; i++) { if (part == itemSheet.getRange(i, 3).getValue()) { var part = itemSheet.getRange(i, 3).getValue(); var unitCost = itemSheet.getRange(i, 5).getValue(); var prodcode = itemSheet.getRange(i, 2).getValue(); } else if (part == itemSheet.getRange(i, 2).getValue()) { var part = itemSheet.getRange(i, 3).getValue(); var unitCost = itemSheet.getRange(i, 5).getValue(); var prodcode = itemSheet.getRange(i, 2).getValue(); } }; // POPULATE PO SHEET poSheet.getRange(lastrowPO, 1).setValue(prodcode); poSheet.getRange(lastrowPO, 2).setValue(part); poSheet.getRange(lastrowPO, 3).setValue(quantity); poSheet.getRange(lastrowPO, 4).setValue(unitCost).setNumberFormat("#,###.00"); };
  1. Uso este código para hacer coincidir el texto de la hoja 1 y tomar una fila de datos de la hoja 2 que coincida con ese texto y devolver los datos a la hoja 1.
  2. Lleva mucho tiempo correr.
  3. Quiero que funcione más rápido. ¿Puede alguien por favor guiarme?
  4. Soy un codificador aficionado.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Descripción

No puedo probar esto, pero básicamente lo que hice fue cambiar su getValue/setValue a getValues/setValues. Por lo general, esto mejora drásticamente el rendimiento.

Algunas partes de su lógica no las entendí del todo, pero traté de duplicarlas tal como están. Por ejemplo, cambia prodcode a part en el bloque else. Y en lugar de continuar con el bucle una vez que he encontrado una coincidencia, break del bucle.

Usando la matriz de items , la fila 1 de la hoja de cálculo es el primer índice 0 de la matriz. Asimismo, la columna 1 de la hoja de cálculo es el segundo índice 0 de la matriz.

Código.gs

 function AddItem() { //DEFINE ALL ACTIVE SHEETS` var ss = SpreadsheetApp.getActiveSpreadsheet(); //DEFINE MENU SHEET ` var poSheet = ss.getSheetByName("POF"); var itemSheet = ss.getSheetByName("Products"); //GET NEXT ROW OF PO SHEET` var lastrowPO = poSheet.getLastRow() + 1; //GET LAST ROW OF ITEM SHEET` var lastrowItem = itemSheet.getLastRow(); // GET VALUE OF PART AND QUANTITY` var part = poSheet.getRange('B15').getValue(); var quantity = poSheet.getRange('B17').getValue(); // Use getValues to get all data var items = itemSheet.getDataRange().getValues(); // GET UNIT PRICE FROM ITEM SHEET // Here I'm assuming you want from row 2 to the last row // And I'm assuming you want the first occurance of part for( var i = 1; i < items.length; i++ ) { if( part == items[i][2] ) { var unitCost = items[i][4]; var prodcode = items[i][1]; break; } else if( part == items[i][1] ) { var prodcode = part; part = items[i][2]; var unitCost = items[i][4]; break; } }; // POPULATE PO SHEET // To use setValues it must pass a 2D array of 1 row poSheet.getRange(lastrowPO,1,1,4).setValues([[prodcode,part,quantity,unitCost]]); poSheet.getRange(lastrowPO, 4).setNumberFormat("#,###.00"); };

Referencia

  • Mejores prácticas
  • Rango.getValues()
  • Rango.establecerValores()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda