使用C#删除书签内容而不删除MS Word中的书签 [英] Delete contents of bookmark without deleting bookmark in ms word using c#

查看:395
本文介绍了使用C#删除书签内容而不删除MS Word中的书签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ms word2010中,我有一个书签,其书签名称为:nameOfBookmark

In ms word2010 I have a bookmark with bookmark name: nameOfBookmark

现在,书签内容可以是任何内容,从文本到图片,表格的混合,以及您想放入Word文档中的任何内容.

Now the bookmark content could be anything from just text to a mix of pictures, tables and whatever you could think of putting in a word document.

问题如下: 我的书签中包含一些要删除的内容.但是,每次我尝试删除内容时,它也会同时删除我要保留的书签.

The problem is as following: I've got my bookmark with some contents I want to delete. However each time I try to delete the contents it also deletes my bookmark which I want to keep.

我已经尝试过了,只是删除了整个内容:

I've tried this, which simply deletes the whole thing:

    public void cleanBookmark(string bookmark)
    {
        var start = currentDocument.Bookmarks[nameOfBookmark].Start;
        var end = currentDocument.Bookmarks[nameOfBookmark].End;
        Word.Range range = currentDocument.Range(start, end);
        range.Delete();
    }

我还尝试将范围设置为此:

I've also tried to set the range to this:

Word.Range range = currentDocument.Range(start +1, end -1);

但是最后我得到一个书签,该书签仍然包含我要删除的内容的第一个和最后一个字符.

But then I end up with a bookmark that still contains the first and the last character of the content I wanted to delete.

推荐答案

好吧,我想知道为什么我必须继续回答自己的问题,如果您认为这可能与我提出问题的方式有关,请通知我.

Well I wonder why I have to keep answering my own questions, please notify me if you think it could be something about the way I ask questions.

无论如何,经过更多的研究,我找到了解决方案,似乎我想做的事情根本无法完成,或者至少不是我认为可以完成的方式.

Anyway I found a solution after a bit more research and it seems like the thing I want simply can't be done or at least not the way I thought it could be done.

如果删除书签的内容,还将删除该书签.因此,您要做的就是将书签的名称和范围存储在本地变量中,然后在删除书签后再次添加书签.

If you delete the contents of a bookmark it also deletes the bookmark. So what you have to do is to store the name and range of the bookmark in a local variable and then add the bookmark again after deleting it.

    public void cleanBookmark(string bookmark)
    {
        var start = currentDocument.Bookmarks[bookmark].Start;
        var end = currentDocument.Bookmarks[bookmark].End;
        Word.Range range = currentDocument.Range(start, end);
        range.Delete(); 
        //The Delete() only deletes text so if you got tables in the doc it leaves the tables empty. 
        //The following removes the tables in the current range.
        if (range.Tables.Count != 0)
        {
            for (int i = 1; i <= range.Tables.Count; i++)
            {
                range.Tables[i].Delete();
            }
        }
        currentDocument.Bookmarks.Add(bookmark, range);
    }

如果您想了解更多有关此主题的信息,请参见

If you want to read more about this topic see this question.

这篇关于使用C#删除书签内容而不删除MS Word中的书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆