我试图首先找到一个段落,然后在用户单击按钮时,对该段落进行一些操作。
我尝试使用似乎是权威书籍的示例:迈克尔·兹拉特科夫斯基(Michael Zlatkovsky)的“ Building Office Addins”。
var global_paragraph = undefined;
async function analyzeDocument() {
Word.run(async function(context) {
const paragraphs = context.document.body.paragraphs;
context.load(paragraphs, 'text');
return context.sync().then(() => {
for (let i = 0; i < paragraphs.items.length; i++) {
if (/*some condition that works only once*/) {
global_paragraph = paragraphs.items[i];
global_paragraph.track();
}
};});
}).catch(handleError);
};
async function handleButtonClick() {
OfficeExtension.config.extendedErrorLogging = true;
Word.run(global_paragraph, async function(context) {
global_paragraph.load("text");
return context.sync().then(() => {
/* do something */
});
}).catch(handleError);
};
这导致了常规异常。
{"code":"GeneralException","message":"GeneralException","errorLocation":"Document._GetObjectByReferenceId","statement":"var v=context.root._getObjectByReferenceId(\"p!00000DB2\");","surroundingStatements":["// >>>>>","var v=context.root._getObjectByReferenceId(\"p!00000DB2\");","// <<<<<","v.load([\"text\"]);"],"fullStatements":["var v=context.root._getObjectByReferenceId(\"p!00000DB2\");","v.load([\"text\"]);"]}
答案 0 :(得分:1)
我能够在Script Lab中重现您的问题。
我认为问题不在于您的代码,而在于Word API。好消息是,有一个简单的解决方法,尽管我仍然鼓励您在https://github.com/officedev/office-js/issues上提交一个错误,以确保产品团队可以调查一下。
解决方法代替
global_paragraph = paragraphs.items[i];
改为:
global_paragraph = paragraphs.items[i].getRange();
通过调用getRange()
,它将创建一个具有正确标识的新对象,从而可以在以后对其进行跟踪。
我在Script Lab中使用的代码段(实际上与您使用的代码段相同)如下:
$("#button1").click(() => tryCatch(button1));
$("#button2").click(() => tryCatch(button2));
var global_paragraph: Word.Range;
async function button1() {
await Word.run(async function(context) {
const paragraphs = context.document.body.paragraphs;
context.load(paragraphs, "text");
return context.sync().then(() => {
for (let i = 0; i < paragraphs.items.length; i++) {
if (paragraphs.items[i].text.startsWith("Dear")) {
global_paragraph = paragraphs.items[i].getRange();
global_paragraph.track();
}
}
});
});
}
async function button2() {
OfficeExtension.config.extendedErrorLogging = true;
Word.run(global_paragraph, async function(context) {
global_paragraph.load("text");
return context.sync().then(() => {
console.log(global_paragraph.text);
});
});
}
/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
// Note: In a production add-in, you'd want to notify the user through your add-in's UI.
console.error(error);
}
}
(当然,要对HTML进行相应的更改以添加两个按钮):
<button id="button1" class="ms-Button">
<span class="ms-Button-label">Button1</span>
</button>
<button id="button2" class="ms-Button">
<span class="ms-Button-label">Button2</span>
</button>
希望这会有所帮助,
〜迈克尔