I have a range consisting of a variable number of rows and 4 columns (A,B,C,D). I need to loop through each of the rows and add the number in column D to the number in column C and then clear the contents of column D. I think I can get the adding and the clearing if i can get the correct cells referenced. i was wanting to use a for or foreach loop and then offset from column A to columns C & D but have been unable to get the offset to work.
function AddInventory2() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Total Inventory')
const lrow = sh.getLastRow();
var Avals = sh.getRange("A1:A"+lrow).getValues();
var Alast = lrow - Avals.reverse().findIndex(c=>c[0]!='');
Avals.forEach(function(row){
targetCell = Avals.offset(0,3);
Logger.log(targetCell);
})
}
2
Answers
Avals.offset(0,3) does not work because Avals is a JavaScript array, not a Range object. Offset only works with Range objects in Google Apps Script.
@EzraMartin I still don’t fully understand the meaning of offset from column A to columns C & D. However, if you want to loop each row and add the number in column D to the number in column C, then clear column D, you can try the following function:
Using offset within a for loop:
The code below achieved the desired requirement of offsetting to columns C & D from each of the cells in column A that contain a value.
Note: However, I wouldn’t suggest using offset in a loop if you have more complex data, as it can increase the number of calls to the Spreadsheet service, which may slow down execution and cause runtime issues.
Code:
Alternative way for a more complex dataset:
In the future, if you have a large dataset, this approach is much better than the first one. It handles large datasets more efficiently by processing the
data in memory
and reducing the number of service calls.Sample Output:
Reference:
Class Range
for