Search code examples
google-sheetsgoogle-sheets-formula

Merging categories on Google Sheets but data will be unclear


Sorry in advanced for bad English. I have 15+ rows and 15+ columns. I need to merge cells in a spreadsheet but data will be unclear after merging. Is there a formula/function I can use to clarify my merge? Thank you in advance.

Please view example spreadsheet.


Solution

  • This is not possible using only formula. Formulas can't do anything to formatting like merging cells and applying colors to text. But here's a script you can use to begin with. You may modify it to apply font color.

    Try:

    function myFunction() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sourceSheet = ss.getSheetByName("Sheet1");
      var destSheet = ss.getSheetByName("Sheet2");
      var sourceData = sourceSheet.getRange(2, 1, sourceSheet.getLastRow() - 1, sourceSheet.getLastColumn()).getValues();
    
      //Add name to each column, add here if you have more columns
      sourceData.forEach(function (x) {
        x[2] = x[1] + ":\n" + x[2]
        x[3] = x[1] + ":\n" + x[3]
      });
    
      var array = sourceData,
        hash = {},
        i, j,
        result,
        item,
        key;
    
      for (i = 0; i < array.length; i++) {
        item = array[i];
        key = item[0].toString();
        if (!hash[key]) {
          hash[key] = item.slice();
          continue;
        }
        for (j = 1; j < item.length; j++) hash[key][j] = hash[key][j] + "\n" + item[j];
      }
    
      result = Object.values(hash);
      destSheet.getRange(2, 1, result.length, result[0].length).setValues(result);
    }
    

    Result:

    enter image description here

    Reference: How to merge an array of arrays with duplicate at index 0 into one array javascript

    Hope this helps!