简体   繁体   中英

How to insert a cell with value on every Nth row in a column in Google Sheets

There is a list of different values as a continuos list (array) in a column.
We need them grouped and separated every Nth row (7th) in another column by inserting some text between them. Not a whole row. Just a cell . As a result they will be "pushed-down" the column.

I have so far tried and succeeded on having the desired result by using a simple query:

I wonder though. Is there a more "elegant" as well as general way using either formula or script .

I suggest you the following solution based on Apps Script:

function myFunction() {
  var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var firstRow=1;
  var column=2;
  var destColumn=3;
  var increment=7;
  var lastRow=sheet.getLastRow();
  var values=sheet.getRange(firstRow, column, lastRow,1).getValues();
  var array=[];
  var k=1;
  Logger.log(lastRow);
  for(var i=0;i<lastRow;i++){
    if(i%increment==0){
      array.push("Group "+k);
      k++;
    }
     array.push(values[i][0]);
  }
  var outerArray = [];
  for(var j=0;j<array.length;j++){
    var tempArray = [];
    tempArray.push(array[j]);
    Logger.log(array[j]);
    Logger.log(tempArray);
    outerArray.push(tempArray);
  }
  sheet.getRange(1, destColumn, array.length, 1).setValues(outerArray);
}

Workflow:

  • Push the contents of the column of interest into an array
  • Insert an additional entry with content every increment th time
  • Transpose the array into the [column][row] syntax
  • Insert the values into the destination column

References:

You could use Array.splice to insert arrays every Nth row:

 /** * Inserts string every nth row * * @customfunction * @param {Object[][]} arr Input Column * @param {number} every Nth row to insert * @param {string} str String to insert */ function insertText(arr, every, str) { for ( var i = 0, j = 0; i < arr.length - 1 && arr.splice(i++, 0, [str + ++j]); i += every ); return arr; } const arr = [ //Input col A1:A25 looks like this ['Sunday'], ['Monday'], ['Tuesday'], ['Wednesday'], ['Thursday'], ['Friday'], ['Saturday'], ['10'], ['20'], ['30'], ['40'], ['50'], ['60'], ['70'], ['MERCURY'], ['MARS'], ['JUPITER'], ['VENUS'], ['SATURN'], ['EARTH'], ['NEPTUNE'], ['Mary'], ['John'], ['Paul'], ['Ann'], ]; console.log(insertText(arr, 7, 'Group'));

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