From a google sheets macro, I am trying to copy a variable range of cells, which depends on the amount of non-empty cells each time. In the following sentence:
spreadsheet.getRange ('Orders! 1: 30'). copyTo (spreadsheet.getActiveRange (), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
I need that instead of the number "30" there is a variable that is defined according to how many lines are occupied in column I of the same sheet.
I was thinking of using the "for" function to scan lines in column I from the cell I1 until It finds an empty one (or not greater than 0). but I'm not sure how to do this.
After the help of #Iamblichus and #Tedinoz I was able to advance in the code, but now a connected and similar problem arised.
I need to paste the selected range in a different tab, but in which same variable no longer recognizes same amount. This is my code:
function Test() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName("Aux");
spreadsheet.getRange('I3:I').createFilter();
var criteria = SpreadsheetApp.newFilterCriteria().setHiddenValues(['0']).build();
spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(9, criteria);
var valuesI = spreadsheet.getRange("I1:I").getValues();
var numRowsI = valuesI.filter(String).length;
var firstRow = 1;
var firstCol = 1;
var numCols = sheet.getLastColumn();
var originRange = sheet.getRange(firstRow, firstCol, numRowsI, numCols);
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Hist_D'), true);
spreadsheet.getActiveSheet().insertRowsBefore(sheet.getActiveRange().getRow(), numRowsI);
spreadsheet.getRange('A1').activate();
originRange.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
originRange.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Aux'), true);
spreadsheet.getRange('T35').activate();
spreadsheet.getActiveSheet().getFilter().remove();
}
"Hist_D" is a record in which the latest data is added at the top. I need to copy a variable amount X of lines from the "Aux" tab to the first lines of the "Hist_D" tab. But before that I need to add (insertRowsBefore) the same number X of lines in "Hist_D" so that the old info is not overwritten. My problem now is how to keep the amount X in the numRowsI variable when changing tabs.
The number of lines inserted through the formula .insertRowsBefore is around 100 (total number of lines in the first tab), when it should be around 20 (number of non-empty lines in the first tab). According to my interpretation, for some reason the variable numRowsI changes when changing tab.