Search code examples
google-apps-scriptmergearray-merge

How to MERGE cells when cells are having same value in a column (GOOGLE SCRIPT)


How to merge cell in a column when cells are having same value

Script 1: Merge cells in column B:B only (Ver/Hor = center/center)

Script 2: Merge cells in column B:B and column E:E (Ver/Hor = center/center)

Sample Here

Regards,


Solution

  • I believe your goal as follows.

    • When the same values are continuously existing in the column direction, you want to merge the cells to the vertical direction in the columns "B" and "E". The following image of sample situation is from your question.

    • You want to achieve this using Google Apps Script.

    In this case, I would like to propose the following sample script.

    Sample script:

    Before you use this script, please set the variables of columns and sheetName. The following sample script merge the columns "B" and "E" of "Shet1".

    function myFunction() {
      const columns = [2, 5]; // These column numbers are the columns "B" and "E". This is from your question.
      const sheetName = "Sheet1";  // Please set the sheetname.
    
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      const [,...values] = sheet.getDataRange().getValues();
      values[0]
      .map((_, i) => values.map(e => e[i]))
      .forEach((col, i) => {
        if (!columns.includes(i + 1)) return;
        let temp = {};
        col.forEach((row, j) => {
          if (row === col[j + 1] && !(row in temp)) {
            temp[row] = j;
          } else if (row != col[j + 1] && row in temp) {
            sheet.getRange(temp[row] + 2, i + 1, (j - temp[row]) + 1, 1).merge();
            temp = {};
          }
        });
      });
    }
    

    References:

    Added:

    About your following additional question,

    The script is perfect. How to modify the script if I want to start at row# 7?

    When above script is modified, it becomes as follows.

    Sample script:

    function myFunction() {
      const columns = [2, 5]; // These column numbers are the columns "B" and "E". This is from your question.
      const sheetName = "Sheet1";  // Please set the sheetname.
    
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      const [,,,,,,...values] = sheet.getDataRange().getValues();
      values[0]
      .map((_, i) => values.map(e => e[i]))
      .forEach((col, i) => {
        if (!columns.includes(i + 1)) return;
        let temp = {};
        col.forEach((row, j) => {
          if (row === col[j + 1] && !(row in temp)) {
            temp[row] = j;
          } else if (row != col[j + 1] && row in temp) {
            sheet.getRange(temp[row] + 7, i + 1, (j - temp[row]) + 1, 1).merge();
            temp = {};
          }
        });
      });
    }