适用于办公室的内容应用程序:如何设置范围并从中读取?

我正在尝试为办公室开发一些简单的内容应用程序。

我想设置一些范围,然后从中读取。 用户必须填写几个框,点击一些button后,应该分析数据。 在VBA或VSTO中这将非常简单,但我必须将其作为办公应用程序来执行。 这个办公室的JavaScript API对我来说是非常不自然的。

一些短的情况:

  1. 用户在Excel中select一些范围,点击某个button,select范围设置为某个公共variables
  2. 用户点击button,function运行,并加载和分析几个范围的数据。

谁能帮忙?

在VBA中:

sub somesub dim rngSomeRange as range dim rngSomeRange2 as range dim rngCell as range dim colValues as new collection dim colValues2 as new collection set rngSomeRange =range("someRange") for each rngCell in rngSomeRange msgbox rngcell.value colValues.add rngcell.value next rngCell for each rngCell in rngSomeRange2 msgbox rngcell.value colValues2.add rngcell.value next rngCell procAnalyze(colValues, colValues2) end sub 

首先,您需要创build一个绑定,以便以后可以引用它:

 var range = "A5:C5"; var id = "numbers"; Office.context.document.bindings.addFromNamedItemAsync(range, "matrix", { id: id }); 

然后,您可以稍后引用此绑定来设置数据:

 var data = [['one', 'two', 'three']]; // 2 dimensional array (matrix) Office.select("bindings#" + id).setDataAsync(data, { coercionType: "matrix" }); 

请注意, addFromNamedItemAsyncsetDataAsync都是asynchronous方法,因此您应该提供一个callback方法来:

  1. 检查结果状态
  2. 确保在写入之前创build绑定

这是一个完整的例子:

 Office.context.document.bindings.addFromNamedItemAsync(range, "matrix", { id: id }, function (asyncResult) { if (asyncResult.status == "failed") { // Error } else { var data = [['one', 'two', 'three']]; // 2 dimensional array (matrix) Office.select("bindings#" + id).setDataAsync(data, { coercionType: "matrix" }, function (asyncResult) { if (asyncResult.status == "failed") { // Error } else { // Success: 'one' is in A5, 'two' is in B5 and 'three' is in C5 } }); } }); 

首先select一些单元格,然后按下一个链接到这个函数的button,它将绑定到这些单元格:

 function bindData() { //A3 Office.context.document.bindings.addFromSelectionAsync("matrix", { id: 'myBindingXXX' }, function (asyncResult) { //NOW DO OUTPUT OR ERROR if (asyncResult.status === "failed") { writeToPage('Error bindData: ' + asyncResult.error.message, 3); } else { writeToPage('Added binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id, 1); } }); } 

现在创build另一个函数来读取绑定,你可以根据需要添加你自己的分析。

 function readBoundData() { //A4 note how id is used here in the binding Office.select("bindings#myBindingXXX").getDataAsync({ coercionType: "matrix" }, function (asyncResult) { //NOW DO OUTPUT OR ERROR if (asyncResult.status === "failed") { writeToPage('Error readBoundData: ' + asyncResult.error.message, 3); } else { writeToPage('Selected data: ' + asyncResult.value , 1); } }); } 

请注意,一旦单元格被绑定,您不必让他们select阅读它们。

有关更多信息,请参阅http://microsoft-office-add-ins.com/