将事件处理程序添加到选定范围

Add an event handler to selected range

我想将事件处理程序添加到用户 select 在工作簿中的范围或单元格中:如果用户 selects 另一个 单元格或范围,需要系统地执行一些操作。

我正在查看this reference,但我不知道在哪里将代码集成到整个加载项中。

例如,在我的Home.html中,我有

    <div id="content-main">
        <div class = "padding" id="message"></div>
        <div class="padding">
            <button class="ms-Button" id="button">Click me!</button>
        </div>
    </div>

这里是Home.js:

(function() {
    "use strict";

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

    function onBindingSelectionChanged(eventArgs) {
        write(eventArgs.binding.id + " has been selected.");
    }
    function write(message) {
        document.getElementById('message').innerText += message;
    }

    function activateEventHandler() {
        Excel.run(function(ctx) {
            var selectedRange = ctx.workbook.getSelectedRange();
            selectedRange.addHandlerAsync(Office.EventType.BindingSelectionChanged, onBindingSelectionChanged); 
            return ctx.sync()
        }).then(function() {
            console.log("done");
        }).catch(function(error) {
            ...
            }
        });
    }        
})();

我希望按钮会激活侦听器。然后,每次用户 select 另一个单元格或范围时,一条消息将系统地附加到任务窗格。但是,上面的代码引发了一个错误:

Error: TypeError: selectedRange.addHandlerAsync is not a function

在第 selectedRange.addHandlerAsync(....

实际上,我什至不确定这段代码的结构应该是这样的...有谁知道如何修改代码来完成我的任务?

错误的原因是您试图在 Range 对象上调用函数 addHandlerAsync。但是处理程序只能添加到 Binding 对象或 Document 对象。你选择哪一个完全取决于你想要完成什么。在您的情况下,我认为您不是在尝试在 specific 范围内收听选择,而是在文档中收听 anywhere 的选择。所以你实际上会使用 DocumentSelectionChanged event:

(function() {
    "use strict";

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

    function onMySelectionChanged(eventArgs) {
        write(eventArgs.binding.id + " has been selected.");
        doStuffWithNewSelection();

    }
    function write(message) {
        document.getElementById('message').innerText += message;
    }

    function activateEventHandler(){
        Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, onMySelectionChanged);
    }

    function doStuffWithNewSelection() {
        Excel.run(function(ctx) {
            var selectedRange = ctx.workbook.getSelectedRange();
            // do other stuff with the selection as you wish, like read and display
        }).then(function() {
            console.log("done");
        }).catch(function(error) {
            ...
            }
        });
    }        
})();