我试图首先找到一个段落,然后当用户单击按钮时,对该段落进行一些操作。
我尝试使用似乎是权威书籍中的示例:Michael Zlatkovsky 的“Building Office Add Ins”。
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\"]);"]}
我可以在脚本实验室中重现您的问题。
我认为问题不在于您的代码,而在于 Word API。好消息是,有一个简单的解决方法,尽管我鼓励您在https://github.com/officedev/office-js/issues https://github.com/officedev/office-js/issues无论如何,要确保产品团队可以调查它。
解决方法是
global_paragraph = paragraphs.items[i];
改为:
global_paragraph = paragraphs.items[i].getRange();
通过致电getRange()
,它创建一个具有适当标识的新对象,因此能够在以后跟踪它。
我在脚本实验室中使用的代码片段(实际上与您的代码片段相同)如下:
$("#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>
希望这可以帮助,
〜迈克尔
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)