我正在尝试循环遍历Word文档中的所有注释,并清除注释文本中包含“CME”子字符串的所有注释。该应用程序是一个用 C# 编写的 VSTO 插件,它使用 .NET 4.8。
我有 2 个问题。
我已经尝试过了。
方法在这里
private void btnClearComments_Click(object sender, RibbonControlEventArgs e)
{
if (Globals.ThisAddIn.Application.ActiveDocument.Comments.Count != 0)
{
// Globals.ThisAddIn.Application.ActiveDocument.DeleteAllComments();
// MessageBox.Show("Clearing All Comments ");
for(int i = 1; i <= Globals.ThisAddIn.Application.ActiveDocument.Comments.Count; i++)
{
if (Globals.ThisAddIn.Application.ActiveDocument.Comments[i].Range.Text.Contains("CME"))
{
Globals.ThisAddIn.Application.ActiveDocument.Comments[i].DeleteRecursively();
}
}
}
else
{
MessageBox.Show("There are No Comments to Delete");
}
}
任何帮助将不胜感激,谢谢。
尝试向后循环:
for (int i = Globals.ThisAddIn.Application.ActiveDocument.Comments.Count; i >= 1; i--)
Comment
对象没有Delete
方法,请参阅docs。
大概也要看评论数吧? Word 中的
Comments
集合是从 1 开始的。从 C# 的角度来看,这是令人困惑的,因为 C# 始终是从 0 开始的。当还剩 1 条评论时,点击即可将其删除。但是,根据评论总数,可能需要多次点击?也就是说,如果我正确理解你的代码。
有几点我想指出。
<= 0
。考虑你的代码:
// imagine we have 3 things, and as with Comments they start counting at 1
// also, let's pretend we run just one iteration
for (counter = 1; i <= things.Count; i++)
{
remove things[counter]; // remove the thing at counter.
}
counter
现在是2,但还剩下2件事。所以下一个循环将再次删除一个东西,但然后留下一个!这不是我们想要的!
Count
属性一次。在本例中,它是对 COM 对象的调用,这是特别昂贵的。但避免不必要的通话总是好的。考虑一下:
private void btnClearComments_Click(object sender, RibbonControlEventArgs e)
{
int nComments = Globals.ThisAddIn.Application.ActiveDocument.Comments.Count; // single call
for (int i = nComments; nComments >= 1 ; i--) // keeping with the index 1 theme
{
if (Globals.ThisAddIn.Application.ActiveDocument.Comments[i].Range.Text.Contains("CME"))
{
Globals.ThisAddIn.Application.ActiveDocument.Comments[i].DeleteRecursively();
}
}
}