2017-01-31 209 views
1

我想引用合并单元格,并从合并单元格范围内的任何单元格获取合并单元格的值。Google电子表格单元格引用合并单元格

在C1中使用=CONCATENATE(A2, " ",B2)并向下拖动它适用于:未合并的单元格和合并单元格的第一个单元格。它不适用于合并组中的后续单元格。这在MS Excel中按预期工作,但不是Google电子表格,有没有办法实现这一点?

Spreadsheet example

回答

2

我写了下面的脚本,它仅适用于合并列的工作(这是我想要的东西):

/** 
* Returns the value at the top of a merged cell. If the merged cell is blank, not at the top of the sheet, and below another merged cell, the the function overflows into the above merged cell and returns incorrect input. 
* 
* @param {int} column Column number of the cell. 
* @param {int} row Row number of the cell. 
* @return The value shown in the merged cell. 
* @customfunction 
*/ 
function FIRST_IN_MERGED_COLUMN(column, row) { 
    var sheet = SpreadsheetApp.getActiveSheet(); 

    var cell = sheet.getRange(row, column); 

    if (!cell.isPartOfMerge()) 
    return cell.getValue(); 
    else if (cell.getValue() != "") 
    return cell.getValue(); 
    else { 
    var r = row; 
    var newCell = cell, oldCell = cell; 
    while (r > 1) { 
     if (!(newCell = sheet.getRange(--r, column)).isPartOfMerge()) 
     return oldCell.getValue(); 
     if (newCell.getValue() != "") 
     return newCell.getValue(); 
     oldCell = newCell; 
    } 
    return ""; // Blank merged cell at top of sheet 
    } 
} 

不幸的是,如果一个合并列的正上方其他合并列,底部的合并列是空的,那么脚本将使用顶部合并列的值。

据下面使用,柱d示出了在列B中的公式,并成功或错误的情况下,在柱中示出C.

enter image description here

0

我发现了一个更好的方法:

// example inputs for cell position 
var row = 5; 
var column = 7; 

// Get the range that the cell belongs and then get the displayed value. 
var cell = sheet.getRange(row, column); 

var result; 

if (!cell.isPartOfMerge()) { 
    result = cell.getValue(); 
} else { 
    // get the range the cell belongs 
    var range = cell.getMergedRanges()[0]; 

    // getting the column and the row of the top left cell in the range 
    var colRef = range.getColumn(); 
    var rowRef = range.getRow(); 

    // getting the value 
    result = range.getDisplayValue(); 
}