google-apps-script - 将数组传递给包装在 ArrayFormula 中的自定义函数?
问题描述
我有一个电子表格,其中包含出于格式化原因使用合并单元格的列。我正在尝试创建反映第一组列但在其所有受影响的行上使用合并单元格值的列。多亏了我在网上找到的自定义功能,我可以做到这一点。然后我不能做的就是将它包含在一个数组公式中,我不知道为什么。
这是电子表格的一个小版本: https ://docs.google.com/spreadsheets/d/1mp8PpgO4sI60bbx__1L4a17qL1VGIB9QVB910vTyhg0/edit?usp=sharing
自定义函数是:
/**
* Takes into account merged cells and returns the value of the merged cell
* for all the cells within the merged range, rother than just the top left
* cell of the merged range.
*
* Copied from https://webapps.stackexchange.com/questions/110277/how-do-i-reference-the-values-of-merged-cells-in-formulas
*
* Used by Patrick Duncan. - 7 May 2018
*/
function cellVal(cellAddress) {
var cell = SpreadsheetApp.getActiveSheet().getRange(cellAddress);
return (cell.isPartOfMerge() ? cell.getMergedRanges()[0].getCell(1, 1) : cell).getValue();
}
没有 Arrayformula 的公式是:
=cellVal2(索引(地址(行(),5,4)))
我正在尝试的是:
=arrayformula(cellVal2(索引(地址(行(E3:E),5,4))))
知道我在这里做错了什么吗?
干杯,
帕特里克
解决方案
这个改装怎么样?我认为您的情况有几种解决方案。因此,请将此视为其中之一。
修改点:
- 什么时候
index(address(row(E3:E30),5,4))
给cellAddress
,cellAddress
是[["E3"], ["E4"], ["E5"],,,]
。这是一个二维数组。- 将这个二维数组展平为
getRangeList()
.
- 将这个二维数组展平为
- 使用 . 将展平数组转换为范围数组
getRangeList()
。 - 使用转换后的范围检索每个值并返回它们。
修改后的脚本:
function cellVal3(cellAddress) { // Modified the function name to "cellVal3"
cellAddress = Array.prototype.concat.apply([], cellAddress);
var cells = SpreadsheetApp.getActiveSheet().getRangeList(cellAddress).getRanges();
return cells.map(function(cell){return [(cell.isPartOfMerge() ? cell.getMergedRanges()[0].getCell(1, 1) : cell).getValue()]});
}
用法 :
当您使用此自定义功能时,请按如下方式使用。
=ARRAYFORMULA(cellVal3(index(address(row(E3:E30),5,4))))
或者
=cellVal3(index(address(row(E3:E30),5,4)))
参考 :
如果我误解了你的问题,我很抱歉。