Import random columns from spreadsheet into order in new spreadsheet - performance

I'm trying to code a script that imports specific columns for a spreadsheet to another spreadsheet. However, currently i'm writing/reading every column separately, which takes quite a while. I do this because I don't need all the columns from the original sheet into the new sheet. I was wondering if my current script could be changed to get to a script where you once read the necessary columns and write them all together? I tried to search for the same but the different order of the columns and the need for specific columns makes it hard.
I hope someone could help me get to the answer.
Thanks in advance,
Tim
function getPDdataupper() {
var sheet = SpreadsheetApp.getActive().getSheetByName('SPR');
var Num = Browser.inputBox("What URL are do you want to copy from?");
var ssraw = SpreadsheetApp.openById(Num);//put Address in here*****
var sheetraw = ssraw.getSheetByName("SPR");
sheet.getRange(10,11,(sheet.getLastRow())-9,3).clearContent();
sheet.getRange(10,1,(sheet.getLastRow())-9,3).clearContent();
//ADJUST ROW
var lastrow = sheet.getLastRow()-10;
var lastrowcopiedsheet = sheetraw.getLastRow()-10;
var diff = lastrowcopiedsheet - lastrow;
if(diff > 0){sheet.insertRowsAfter(11,diff);}
if(diff < 0){sheet.deleteRows(20,(diff*-1)); }
sheet.getRange(11,1,(sheet.getLastRow())-11,33).clearContent();
var values = sheetraw.getRange(1,1,5,1).getValues();
sheet.getRange(1,1,5,1).setValues(values);
var values = sheetraw.getRange(10,3,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,2,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,38,sheetraw.getLastRow()-9,2).getValues();
sheet.getRange(10,3,(sheet.getLastRow()-9),2).setValues(values);
var values = sheetraw.getRange(10,43,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,6,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,44,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,5,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,6,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,7,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,54,sheetraw.getLastRow()-9,2).getValues();
sheet.getRange(10,8,(sheet.getLastRow()-9),2).setValues(values);
var values = sheetraw.getRange(10,58,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,10,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,14,sheetraw.getLastRow()-9,19).getValues();
sheet.getRange(10,14,(sheet.getLastRow()-9),19).setValues(values);
var values = sheetraw.getRange(10,51,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,33,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,62,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,34,(sheet.getLastRow()-9),1).setValues(values);
var values = sheetraw.getRange(10,4,sheetraw.getLastRow()-9,1).getValues();
sheet.getRange(10,35,(sheet.getLastRow()-9),1).setValues(values);

I have sorted it myself now. For someone who is looking for the same thing, please see the code below. If anyone else thinks of something better please feel free to amend.
function getPDdataupper() {
var sheet = SpreadsheetApp.getActive().getSheetByName('SPR');
var folder= DriveApp.getFolderById('FolderID');
var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
while (files.hasNext()) {
var ssraw = SpreadsheetApp.open(files.next());
//var ssraw = SpreadsheetApp.open(Num);
}
sheet.getRange(11,1,(sheet.getLastRow())-10,53).clearContent();
var sheetraw = ssraw.getSheetByName("SPR");
sheet.getRange(10,11,(sheet.getLastRow())-9,3).clearContent();
sheet.getRange(10,1,(sheet.getLastRow())-9,3).clearContent();
//ADJUST ROW
var lastrow = sheet.getLastRow()-10;
var lastrowcopiedsheet = sheetraw.getLastRow()-10;
var diff = lastrowcopiedsheet - lastrow;
if(diff > 0){sheet.insertRowsAfter(11,diff);}
if(diff < 0){sheet.deleteRows(20,(diff*-1)); }
//var values = sheetraw.getRange(10,("C10:C,AL10:AM,AQ10:AR,F10:F,BB10:BC,BF10:BF"),(sheetraw.getLastRow()-9),53).getValues();
//sheet.getRange(10,2,(sheet.getLastRow()-9),(sheet.getLastColumn()-1)).setValues(values);
var data = sheetraw.getDataRange().getValues();{
var target = new Array();
for(n=0;n<data.length;++n){
target.push( [[data[n][2]], [data[n][37]], [data[n][38]], [data[n][43]], [data[n][42]], [data[n][5]], [data[n][53]], [data[n][54]], [data[n][57]]] );
}
sheet.getRange(1,2,target.length,target[0].length).setValues(target);
}

Related

Goggle Sheets - Add Row and sort

Total beginner here so please dumb down your answers lol - How do I add a blank row to a specific row in google sheets that is being sorted without the row moving before I can edit it? I'm happy to change my system as needed.
Basically, I'm building an internal workflow program and have an auto-sort script for a list of jobs, when the jobs are completed the staff change row 1 from "A" to "Z" which pushes that row/job to the bottom of the sheet. However, the problem we have is when we add new work by inserting a row and start typing....the row moves before we can put data into it - it's a pain - what ideas does everyone have where I can improve this?
Thoughts / Ideas?
This is the sort script I have at the moment.
function onEdit(event){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Large")
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
var tableRange = "A9:M100";
if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy } );
}
}
I could find two possible solutions:
1- Use the cell's oldValue, it's value is undefined whenever you add a value to the cell for the first time. Using this solution will sort the table if you change the value a second time:
function onEdit(event){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Large")
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
var tableRange = "A9:M100";
if(editedCell.getColumn() == columnToSortBy && event.oldValue != undefined){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy } );
}
}
2- Sort only if the the cell is changed to Z, update the condition to:
if(editedCell.getColumn() == columnToSortBy && event.oldValue === "Z"){
Reference:
Event Objects

Looping over a dynamic range in Google apps script to replace certain values

I've been getting problems trying to reference a dynamic range in google sheets to apply my function to: essentially replacing special characters and empty cells within a given data range with 0s, works perfectly if I gave it a static range but cant seem to do a dynamic one. Thanks alot for any help offered
Code thus far:
function replaceValues() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var lastRow = sheet1.getDataRange().getLastRow()
var firstRow = sheet1.getDataRange().getRow("B2")
var targetValue1 = '-'
var targetValue2 = ''
var targetValue3 = '$'
var subValue = 0
for(var i =0; i=targetValue1; i++); {
var valueRng = sheet1.getRange(firstRow,lastRow);
var newValues = valueRng.getValues()[i].setValues(subValue);
}
}
Select the range before going the the menu and executing the function or build a modeless dialog and you can make the selection and capture on the custom dialog with a button click.
Demo:
If you have a range, you can do search and replace inside it this way:
range.createTextFinder('aaa').replaceAllWith('b');
Or with RegExp:
range.createTextFinder('a+').useRegularExpression(true).replaceAllWith('b');
I still don't understand what exactly you're trying to gain. So here is a guess how your script might look like:
function replaceValues() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var range = sheet1.getDataRange(); // is the range dynamic enough?
// replace '$' and '-' with '0'
range.createTextFinder("[\$-]").useRegularExpression(true).replaceAllWith('0');
// replace '' with '0'
var data = range.getValues();
data.forEach((row,r) => row.forEach((cell,c) =>
data[r][c] = data[r][c].toString().replace(/^$/,'0')));
range.setValues(data);
}

Google script pushing data from one tab to another while retaining data validation

I have the following google apps script. It functions to look in my PENDING-IP tab and check the status (column G). If the status is "Screened - Ready for Review," then it moves the entire row of data to the SCREENED - READY FOR REVIEW tab.
My problem is this - the data in columns L, M, and N of the PENDING tab is a checkbox, but when it pushes it to the SCREENED tab, it changes it to TRUE or FALSE. Is there a way to modify my script to push the data with validation to retain the checkboxes? Thank you!
function screened() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('PENDING-IP'); //source sheet
var testrange = sheet.getRange('G:G'); //range to check
var testvalue = (testrange.getValues());
var csh = ss.getSheetByName('SCREENED - READY FOR REVIEW'); //destination sheet
var data = [];
var j =[];
//Condition check in G:G; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'Screened - Ready for Review') {
data.push.apply(data,sheet.getRange(i+1,1,1,25).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
//Delete matched rows in the source sheet
for (i=0;i<j.length;i++){
var k = j[i]+1;
sheet.deleteRow(k);
//Alter j to account for deleted rows
if (!(i == j.length-1)) {
j[i+1] = j[i+1]-i-1;
}
}
}
Try this
I haven't actually tested this except in a simpler situation
function screened() {
var ss=SpreadsheetApp.getActive();
var sheet=ss.getSheetByName('PENDING-IP');
var testrange=sheet.getRange(1,7,sheet.getLastRow(),1);
var testvalue=testrange.getValues();
var valids=testrange.getDataValidations();
var csh = ss.getSheetByName('SCREENED - READY FOR REVIEW'); //destination sheet
var data = [];
var valid = [];
var j =[];
var d=0;
for (var i=0;i<testvalue.length;i++) {
if (testvalue[i][0] == 'Screened - Ready for Review') {
data.push(sheet.getRange(i+1-d,1,1,25).getValues());//I am not sure but I could see having to put [0] at the end here
valid.push(sheet.getRange(i+1-d,1,1,sh.getLastColumn()).getDataValidations());//I am not sure but I could see having to put [0] at the end here
sheet.deleteRow(i+1-d++);//this should delete matching rows
}
}
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(valid);
}
What I've found is that you can treat the validations the same way you treat the data by replacing getValues() with getDataValidations() and setValues() with setValidations();

optimise Google Apps script

Could anyone please help me optimise this Google Sheets script?
It's painfully slow. It barely makes 300 copies in 24 hours (I need the Drive API to make the copies as "view only users can't copy/print/download")
function addCopies() {
var count = 10;
var input = DriveApp.getFileById('1GQI5m0g5XsCWi1dOTBWFs3VJkzW7e8N__09C3-2BEGI')
var results = DriveApp.getFileById('1gkOCTPJuqTQnNNlaE3jD2Hq2COU-lO02PmlO_xMepx0')
var indexSH = SpreadsheetApp.openById('1o6ZfweVylhnDXoVc9u_R8afKdVfXYgtdqtj_lSCdFEk').getSheetByName('Index')
for(var i=0;i<count;i++)
{
//make copies of both files (input & results)
var inputCopy = input.makeCopy(input.getName(), DriveApp.getFolderById('0B0go-fsdFA3ISG0xNGlhTDZoM0U'))
inputCopy.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT)
var inputID = inputCopy.getId()
//make results to be restricted using API
var resultsCopy = results.makeCopy(results.getName(), DriveApp.getFolderById('0B0go-fsdFA3ISG0xNGlhTDZoM0U'))
resultsCopy.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW)
var resultsID = resultsCopy.getId()
var apiFile = DriveAPI.Files.get(resultsID)
apiFile.labels.restricted = true
DriveAPI.Files.update(apiFile, resultsID)
//save IDs of both files to an index for later re-use
var lastRow = indexSH.getRange(1,1).getValue()
var addRng = indexSH.getRange(lastRow+1, 1,1,3)
addRng.setValues([['free',inputID,resultsID]])
}
}
Edit: techydesigner said "we don't optimise code on SO" . So please let me rephrase : am I using the wrong Drive services ? Is there a method to make those copies faster ?

Faster Iterative Calculation

I've made a script that performs an iterative calculation to find values based on a gross percentage of project cost.
This is what I have so far:
//<!-- FEE, BOND, & INSURANCE CALCULATOR --!>
function feeBondInsCalculator (){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Pretty Sum Form");
sheet.activate();
// Get all variables from named ranges
var bondValue = ss.getRangeByName("bondValue");
var bondCalc = ss.getRangeByName("bondCalc");
var insValue = ss.getRangeByName("insValue");
var insCalc = ss.getRangeByName("insCalc");
var feeValue = ss.getRangeByName("feeValue");
var feeCalc = ss.getRangeByName("feeCalc");
var interCount = ss.getRangeByName("interCount")
// Interative calculation to paste calculated values into the body of the spreadsheet
for (var i = 0; i<11; i++){
feeCalc.copyTo(ss.getRangeByName("feeValue"), {contentsOnly: true});
bondCalc.copyTo(ss.getRangeByName("bondValue"), {contentsOnly: true});
insCalc.copyTo(ss.getRangeByName("insValue"), {contentsOnly: true});
interCount.setValue(i)
}
}
I used range names so that users can add/delete rows and columns and not have to reset the code. When executed, the code works fine, but takes about two seconds per iteration. Is there a more efficient way to make this work?
Instead of using copy, you might try referencing your ranges directly in a formula like:
=arrayformula(if(bondValue <>"",bondValue,""))

Resources