设置setFormulas()将清除现有数据

时间:2017-02-14 06:28:17

标签: google-apps-script google-sheets google-spreadsheet-api

我想保留那些没有应用公式的细胞的细胞数据。

代码段解释了该功能。

此解决方案也会覆盖值setFormulas won't skip empty array elements, over-writes values

var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
var Formulas = range.getFormulas();


for (var i in Formulas) {
    for (var j in Formulas[i]) {

        if (Formulas[i][j] == "") //cells which dont have the formula
        {
            //dont apply any formula, but keep the existing cell data (as it is)
        } else {
            Formulas[i][j] = '=HYPERLINK("http://www.google.com","Google")'
        }
    }
}

range.setFormulas(Formulas);

1 个答案:

答案 0 :(得分:2)

“copyTo()”可以复制带有值,公式和格式的单元格。 https://developers.google.com/apps-script/reference/spreadsheet/sheet#copyTo(Spreadsheet)

示例脚本如下。

脚本:

var range = ss.getRange('a1:a8');
var values = range.getValues();
var formulas = range.getFormulas();

var destrange = ss.getRange('b1:b8');
range.copyTo(destrange);

var destvalues = destrange.getValues();
var destformulas = destrange.getFormulas();

值:

[[1.0], [5.0], [3.0], [9.0], [1.0], [2.0], [3.0], [24.0]]

公式:

[[], [], [], [=sum(A1:A3)], [], [], [], [=sum(A1:A7)]]

destvalues:

[[1.0], [5.0], [3.0], [9.0], [1.0], [2.0], [3.0], [24.0]]

destformulas:

[[], [], [], [=sum(B1:B3)], [], [], [], [=sum(B1:B7)]]

如果这对你有帮助,我很高兴。