附加所选单元格的公式

Append the formula of the selected cell

我想实现以下场景:用户选择一个包含公式的单元格,单击我的加载项的 test 按钮,然后我的 test 函数读取公式选定的单元格,向其附加 +RAND(),然后将其写回工作簿。

下面的代码读取选中单元格的公式很好,但是回写不好。我不确定(第二个)return ctx.sync() 是否正确使用。

此外,我不知道是否应该在整个场景中使用 getSelectedDataAsyncsetSelectedDataAsync(而不是 getSelectedRange)。

有人能帮忙吗?

(function() {
    "use strict";

    Office.initialize = function(reason) {
        $(document).ready(function() {
            app.initialize();
            $('#test').click(test);
        });
    }
    ;

    function test() {
        Excel.run(function(ctx) {
            var selectedRange = ctx.workbook.getSelectedRange();
            selectedRange.load(["formulas"]);
            return ctx.sync().then(function() {
                console.log(selectedRange.formulas[0][0]);
                var x = selectedRange.formulas[0][0] + "+RAND()";
                selectedRange.formulas[0][0] = x;
                return ctx.sync();
            })
        }).then(function() {
            console.log("done");
        }).catch(function(error) {
            console.log("Error: " + error);
        });
    }
})();

错误是您试图分配给公式上下文对象中的单个元素。而是使用:

selectedRange.formulas = x;

selectedRange.formulas = [[x]];