我正在尝试为办公室开发一些简单的内容应用程序。
我想设置一些范围,然后从中读取。用户必须填写几个框,点击一些按钮数据后应进行分析。在VBA或VSTO中它会非常简单,但我必须将它作为办公室应用程序。这个办公室的JavaScript API对我来说非常不自然。
一些短暂的情景:
有人可以帮忙吗?
在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
答案 0 :(得分:1)
首先,您需要创建一个绑定,以便稍后可以引用它:
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" });
请注意,addFromNamedItemAsync
和setDataAsync
都是异步方法,因此您应该提供一个回调方法:
这是一个完整的例子:
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
}
});
}
});
答案 1 :(得分:0)
首先选择一些单元格然后按下链接到此功能的按钮,它将绑定到这些单元格:
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);
}
});
}
现在创建另一个函数来读取绑定,您可以根据需要添加自己的分析。
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);
}
});
}
请注意,一旦单元格被绑定,您不必选择它们来读取它们。
有关详细信息,请参阅http://microsoft-office-add-ins.com/