无法删除 VSTO C# Word Add In 中的所有注释

问题描述 投票:0回答:2

我正在尝试循环遍历Word文档中的所有注释,并清除注释文本中包含“CME”子字符串的所有注释。该应用程序是一个用 C# 编写的 VSTO 插件,它使用 .NET 4.8。

我有 2 个问题。

  1. 删除方法不在我可以在此处选择的方法列表中 Globals.ThisAddIn.Application.ActiveDocument.Comments[i]
  2. 当我使用DeleteRecursively()方法时,它不会删除所有评论,而是留下一条评论,我必须再次单击功能区上的清除评论按钮才能删除最后一条评论。

我已经尝试过了。

  1. 我已经通过 nuget 安装了 Office 互操作库。
  2. 我尝试在集合中的评论上寻找其他方法,但没有找到任何有效的方法。
  3. 在网上搜索了一下。

方法在这里

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");                

            }            

        }

任何帮助将不胜感激,谢谢。

c# vsto add-in
2个回答
0
投票

尝试向后循环:

for (int i = Globals.ThisAddIn.Application.ActiveDocument.Comments.Count; i >= 1; i--)

0
投票
  1. Comment
    对象没有
    Delete
    方法,请参阅docs

  2. 大概也要看评论数吧? 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件事。所以下一个循环将再次删除一个东西,但然后留下一个!这不是我们想要的!

  • @Dmitry 因此建议以相反的顺序进行删除是正确的。
  • 这还有一个额外的好处,那就是只需调用
    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();   
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.