简体   繁体   中英

Google Sheets scripts to add rows based on a cell value

can someone please help me with the script

I want to add 9 rows after the first row, 4 rows after the second row basically adding rows based on the Column D value mentioned in the screenshot

在此处输入图片说明

Adding rows

The key to situations where your adding or removing rows is to use a counter to keep track of the changing number of rows. By using getDataRange() the index i is normally one less than the row number until it begins to add rows so the add counter a bridges the gap between the index of fixed 2d array v and the rows that are added between the old rows which we're read to assemble the 2d array v in the rg.getValues() line.

function addingRows() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getDataRange();
  var v=rg.getValues();
  var a=0;
  //r[3] is column 4
  //The forEach is appropriate here since we know we have to iterate through the entire array with no need for breaking out
  v.forEach(function(r,i){
    if(r[3]>0) {
      sh.insertRowsAfter(i+1+a,r[3]);//i+1+a is the row number
      a+=r[3];//increased by the number of rows which were just added
    }
  });
}

Sheet.insertRowsAfter

Animation:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM