I have an issue with a slow speed of my Google Apps Script containing a loop. I'm looking for recommendations how to increase the speed.
I have the following input data on a sheet named "Test" (just an extract for demonstration purposes but have in mind that the original data is much larger - with much more products and suppliers):
I want to achieve on a separate sheet named "Suppliers" the following result:
The idea is the suppliers with their respective products and prices to be reorganized in the format shown above. The conditions are:
- Exclude inactive products;
- Exclude inactive suppliers;
- include only products per supplier with an available price;
- Dynamic update of the data when adding new products/ suppliers, or changing anything on the input table.
I have done the following script - it's working, but speed is quite slow considering the fact that original data is large. I would highly appreciate any advises how to optimize it. I spent much time trying to optimize it by myself but to no avail. Many thanks in advance!
function Suppliers() {
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheetSourceName = 'Test';
var sheetDestinationName = 'Suppliers';
var sourceSheet = file.getSheetByName(sheetSourceName);
var numRows = sourceSheet.getLastRow();
var numCols = sourceSheet.getLastColumn();
var destinationSheet = file.getSheetByName(sheetDestinationName);
var sheet = file.getActiveSheet();
if( sheet.getSheetName() == sheetSourceName ) {
var lastRow = destinationSheet.getLastRow();
destinationSheet.getRange( 2, 1, lastRow, 3 ).clear( { contentsOnly : true } );
var lastRow = 1;
for( var s = 3; s < numCols + 3; s++ ){
for( var p = 3; p < numRows + 3; p++ ){
var product = sourceSheet.getRange( p, 2 ).getValues();
var activeProduct = sourceSheet.getRange( p, 1 ).getValues();
var price = sourceSheet.getRange( p, s ).getValues();
var supplier = sourceSheet.getRange( 2, s ).getValues();
var activeSupplier = sourceSheet.getRange( 1, s ).getValues();
if( activeProduct == "active" && price > 0 && activeSupplier == "active" ){
lastRow = lastRow + 1;
destinationSheet.getRange( lastRow, 1 ).setValues( product );
destinationSheet.getRange( lastRow, 2 ).setValues( price );
destinationSheet.getRange( lastRow, 3 ).setValues( supplier );
}
}
}
}
}