Loop and export only one tab - loops

I have a script that's working well - it takes a value from a list (employee ID) and inserts it into the 'Scorecard' tab - the script then outputs all employee scorecards as .pdfs. Only problem I'm running into is the script is exporting both tabs to the .pdf as opposed to only the scorecard... any thoughts?
function loop() {
var targetFolderId = "11rc9rFM25lnLArxm0yk588UEH5MD-NpR";
var targetFolder = DriveApp.getFolderById(targetFolderId);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var validation_sheet = ss.getSheetByName('Performance_Scores');
var lastRow = validation_sheet.getLastRow();
var inputs = ss.getSheetByName('Performance_Scores').getRange('A2:A'+lastRow).getValues();
var tab = ss.getSheetByName('Scorecard');
//Loop
for (var i = 0; i < inputs.length; i++) {
tab.getRange('B2').setValue(inputs[i][0]);
SpreadsheetApp.flush();
Utilities.sleep(5000);
//Print PDFs
var name = tab.getRange(2, 2).getValue();
targetFolder.createFile(ss.getAs('application/pdf')).setName(name);
}
}

Try this:
function loop() {
var targetFolder=DriveApp.getFolderById("11rc9rFM25lnLArxm0yk588UEH5MD-NpR");
var ss=SpreadsheetApp.getActive();
var validation_sheet=ss.getSheetByName('Performance_Scores').hideSheet();
var inputs=validation_sheet.getRange(2,1,validation_sheet.getLastRow(),1).getValues();
var tab=ss.getSheetByName('Scorecard').showSheet();
for (var i=0; i < inputs.length; i++) {
tab.getRange('B2').setValue(inputs[i][0]);
SpreadsheetApp.flush();
Utilities.sleep(5000);
var name=tab.getRange(2, 2).getValue();
targetFolder.createFile(ss.getAs('application/pdf')).setName(name);
}
}

Related

How can I improve speed of for loops in Google Sheets app script?

I know I must use array to improve speed when use for loop but I don't understand how to do that? How can I rewrite this code?
function hiliptk() {
//var I_INDEX = 1;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var dataValues = dataRange.getValues();
for (var i=3; i<=98; i++) {
var row = sheet.getRange(i, 1, 1,9);
if (sheet.getRange(i,2).getValue()== "PTK") {
row.setBackground("yellow");
} else {row.setBackground("white");}
}
}
This part of your code var dataValues = dataRange.getValues(); will return a 2 dimensional array containing the data in your sheets. You can use the 3rd element of each sub-array to check whether it is "PTK" or not.
Example:
function hiliptk() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var dataRange = sheet.getDataRange();
var dataValues = dataRange.getValues();
var rangeListYellowBG = [];
var rangelistWhiteBG = [];
//this loop collects the range by the value of column C
for (var i=2; i<dataValues.length; i++){
if(dataValues[i][2] == 'PTK'){
//push to array rangeListYellowBG if column C is 'PTK'
rangeListYellowBG.push("A"+parseInt(i+1)+":I"+parseInt(i+1));
}else{
//else push to rangelistWhiteBG
rangelistWhiteBG.push("A"+parseInt(i+1)+":I"+parseInt(i+1));
}
}
//this will change the background color of the following range to yellow [A5:I5, A8:I8, A11:I11, A12:I12]
sheet.getRangeList(rangeListYellowBG).setBackground("yellow");
//this will change the background color of the following range to white [A3:I3, A4:I4, A6:I6, A7:I7, A9:I9, A10:I10, A13:I13]
sheet.getRangeList(rangelistWhiteBG).setBackground("white");
}
Sample Data:
Output:
References:
array.push()
getRangeList()

Issue with Google Apps Script code copy-paste from Gsheet file

I've created a code to copy-paste the values from the most recent uploaded Gsheet file to another. The code is supposed to copy-paste only values that fulfil a cell condition.
The problem is, this code takes to long to run and doesn't finish to copy all values before having a run-time error.
The file has about 300.000 cells and the final amounts to be pasted on the 2nd file have about 90.000 cells.
Does anyone have a recommendation on how to proceed?
Thank you so much for your kind support.
function Master_Run_DB() {
Copy_EUDB();
}
function Copy_EUDB() {
var myLink = extractLink_EUDB();
sendData_EUDB(myLink);
}
function extractLink_EUDB() {
var newData = new Date().toLocaleString();
var drive = DriveApp.getFolderById("link to file");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.getActiveSpreadsheet();
return link
}
function sendData_EUDB(link) {
var mainSS = SpreadsheetApp.openById("link to file");
var lastRow = mainSS.getSheetByName("Database").getLastRow();
mainSS.getSheetByName("Database").getRange("A2" + ":R" + lastRow).clearContent();
var baseSS = SpreadsheetApp.openByUrl(link);
Logger.log(SpreadsheetApp.getActiveSpreadsheet().getUrl());
var lRow = baseSS.getSheetByName("Sheet1").getLastRow();
for (var i = 2; i <= lRow; i++) {
var cell = baseSS.getRange("G" + i);
var val = cell.getValue();
if (val == "EU") {
var sourceData = baseSS.getSheetByName("Sheet1").getRange("A" + i + ":R" + i).getValues();
var to = mainSS.getSheetByName("Database").getRange("A" + i + ":R" + i).setValues(sourceData);
}
}
};
Hello again,
Now that the new code is working, I was trying to add an IF AND clause to the copy-paste. The objective would be to copy only values that fulfil the following condition:
Column 7 = "EU"
Column 11 <> "CCCC"
But I'm getting a Syntax Error. Any advice?
Thank you in advance for your kind support
function Master_Run_EU() {
var drive = DriveApp.getFolderById("link to file");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("link to file");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),22).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var oA=[];
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,22).getValues();
vs.forEach(function(r,i){
if(r[7]=="EU" && r[11]<>"CCCC") {
oA.push(r);
}
});
sh.getRange(2,1,oA.length,oA[0].length).setValues(oA);
}
Try this:
function Master_Run_DB() {
var drive = DriveApp.getFolderById("1ViOyzIkGOI6G6SMrtmPv4vjL-2-2duHC");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("13CchyoqiWyvGTnYuG5TWA4cggBS-FsoDkW8XGesDkiY");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),18).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,18).getValues();
vs.forEach(function(r,i){
if(r[6]=="EU") {
sh.getRange(i+2,1,1,18).setValues([r]);
}
});
}
It would be faster to do it this way:
function Master_Run_DB() {
var drive = DriveApp.getFolderById("1ViOyzIkGOI6G6SMrtmPv4vjL-2-2duHC");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("13CchyoqiWyvGTnYuG5TWA4cggBS-FsoDkW8XGesDkiY");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),18).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var oA=[];
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,18).getValues();
vs.forEach(function(r,i){
if(r[6]=="EU") {
oA.push(r);
}
});
sh.getRange(2,1,oA.length,oA[0].length).setValues(oA);
}

Google Script array value undefined

i wrote a code that should take a value from a cell and than convert it to the string and than into the array. its working fine. I can see the value of arr in Logs as an array with the input of the cell. For example, in the cell are " dog, cat " and tha arr value in Logs is [dog, cat].
But after i create this array, i would like to make a loop on it. And than i become in Logs, that arr is undefined. Can somebody help me please? im working on it for 2 days :(
Here is my code:
function animal (s,z){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange("SM");
var columnNumber = getColumnNumberOfSM(s);
var rowNumber = getRowNumberOfSM(z);
var colAction = columnNumber + 1;
var action = sheet.getRange(rowNumber, colAction, 1, 1).getValues();
var bar = action.toString();
var arr = [{}];
arr = bar.split(", ");
//return arr; // returns an array [dog, cat]
var foo = arr; // underfined
for (var i = 0; i <= foo.length; ++i) {
if (foo[i] == "dog") {
Logger.log(upload());
}
}
}
now i edit my code and its working fine,but only with "dog" but not with "cat"
function animal(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var action = sheet.getRange("C3").getValue();
var bar = action.toString();
var arr = bar.split(", ");
for (var i = 0; i <= arr.length; ++i) {
if (arr[i] == "dog") { // works
Logger.log(upload());
}
if (arr[i] == "cat") { // doesn't work
Logger.log(upload());
}
}
}
You don't need to initiate arr as blank you can directly initialize it as a result to split method , also one point I didn't get is why do you need to assign arr to foo? You can directly iterate through arr.length and perform the required operation.
Here's my working snippet.
var parts = path.split(",");
for (var i = 0; i < parts.length; i++) {
if (parts[i] == 'dog'){
Logger.log(parts[i]);
}
}

Angularjs - get selected values by each function

How can I implement the following function in Angularjs?
var TEST = [];
$('#div').find('select.test').each(function(){TEST.push($(this).val())});
And then with this values I would like update the ng-model value, like this:
$scope.formData.TEST = TEST.join(",");
This is my solution:
var TEST_ITEMS = [];
var testValues = document.getElementsByClassName('test');
for (var i = 0; i < testValues.length; ++i) {
var item = testValues[i];
var _testValues = item.options[item.selectedIndex].value;
console.log(_testValues);
TEST_ITEMS.push(_testValues);
}
$scope.formData.TEST = TEST_ITEMS.join(",");

Google Scripts For Loop

I'm trying to insert some data from a spreadsheet into a different spreadsheet, the problem is that the loop is not behaving as expected, it only gives me one entry in the target spreadsheet. I've tried using while and no function but it didn't work.
Here is the code:
function move(){
var homeBook = SpreadsheetApp.getActiveSpreadsheet();
var sheet = homeBook.getSheets()[0];
var limit = sheet.getLastRow(); //number of rows in the sheet
var evento = sheet.getRange(2, 1, limit-1).getValues(); //event list
var descript = sheet.getRange(2,2,limit-1).getValues(); //description list
var tags = sheet.getRange(2,3,limit-1).getValues(); //tag list
var sheetsIDHome = sheet.getRange(2,4,limit-1).getValues(); //ID list
var targetBook = SpreadsheetApp.openById("1t3qMTu2opYffLmFfTuIbV6BrwsDe9iLHZJ_ZT89kHr8"); //target workbook
var target = targetBook.getSheets()[0]; //Sheet1
var targetLimit =target.getLastRow(); //Rows with content
var sheetsIDTarget = target.getRange(targetLimit, 4); // ID list
var targetRow = targetLimit+1; //row where content is going to be inserted
for(i = 2;i <= limit;i++){//loop for each value to be inserted in each row of the target sheet
(function(x){
target.getRange(targetRow,1).setValue(x);
target.getRange(targetRow,2).setValue(descript[2]);
target.getRange(targetRow,3).setValue(tags[3]);
target.getRange(targetRow,4).setValue(sheetsIDHome[4]);
targetRow = targetRow++;
})(i);
};
You're trying to access the four arrays created from the values for columns 1-4.
Your for statement needs to match their structure, starting with the first array instance of 0. You can use any of the arrays for the iteration, I've chosen the first.
In addition, I've removed the function and replaced x with the instance from evento.
++ increments the value of the variable, no need for assignment there.
for (var i = 0; i < evento.length; i++) {
target.getRange(targetRow,1).setValue(evento[i]);
target.getRange(targetRow,2).setValue(descript[i]);
target.getRange(targetRow,3).setValue(tags[i]);
target.getRange(targetRow,4).setValue(sheetsIDHome[i]);
targetRow++;
}
there is a code that has been mis-placed, kindly check my code below:
function UpdateBSRSpecial()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var testForm = ss.getSheetByName("ENTRY FORM");
var testTable = ss.getSheetByName("BSR DATA");
var testFormValue = testForm.getRange("G6").getValue();
var rangeData = testTable.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
for(var i=2;i<=lastRow;i++){
var dataID = testTable.getRange(i,1).getValue();
if(testFormValue == dataID)
{
testTable.getRange(i,6).setValue("new value");
};
};
};
hope this helps

Resources