MS Word Interop到C#-在书签中插入多个文件 [英] MS Word Interop to C# - Inserting multiple files at a bookmark

查看:76
本文介绍了MS Word Interop到C#-在书签中插入多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主文档,我想在其中插入许多文件.这些文件应该在文档中间的某个位置一个接一个地插入文件中.

I have one master document into which I want to insert a number of files. These should be inserted into the file one after another at a certain point in the middle of the document.

因此,我此时创建了一个名为"TESTS"的书签,因为这似乎是通过编程方式找到该点的最简单方法.

So I have created a bookmark at this point called "TESTS", since this seems to be the easiest way of programatically finding the point.

我可以使用以下代码插入单个文件:

I am able to insert a single file using this code:

 Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
 Microsoft.Office.Interop.Word.Document oWordDoc = oWord.Documents.Open(@"C:\master.doc");
 oWordDoc.Bookmarks.Cast<Bookmark>().First(b => b.Name == "TESTS").Range.InsertFile(@"C:\test1.doc");

但这会删除书签,从而无法在同一点插入第二个文件.我不介意丢失书签,而只是在插入所有文件之后.

But this removes the bookmark, making it impossible to insert a second file at the same point. I don't mind losing the bookmark, but only once I have inserted all files.

可以做到吗?我猜想上面的代码用书签替换了范围,所以最好在之前或之后找到位置,然后删除书签范围是最好的-但我只是找不到它的代码.我尝试过的一切似乎都可以代替整个文档.

Can this be done? I am guessing that the above code replaces the range with the bookmark so finding the location just before or after and then deleting the bookmark range would be best - but I just can't find the code for it. Everything I have tried seems to replace the whole document.

或者,没有Interop,有没有办法做到这一点(即通过解析文件-完全不接触MS Word)?

Alternatively, is there any way to do this without the Interop (i.e. by parsing the file - no touching MS Word at all)?

推荐答案

关于文档的设置方式和书签的确切范围,必须有一些特别之处,因为我能够在不丢失文档的情况下使它起作用书签.根据此MVP文章在不删除书签的情况下在书签中插入文本,并添加了文本到书签范围应该删除书签;也许您遇到了InsertFile的类似问题.

There must be something particular about the way your document is set up and the exact range of the the bookmark because I am able to get this to work without losing the bookmark. According to this MVP article Inserting text at a bookmark without deleting the bookmark, adding Text to a bookmarked range should delete the bookmark; maybe you are running into similar issue with InsertFile.

尝试他们的建议,将书签的范围存储到变量中,即MyRange,然后调用Bookmarks.Add "mybookmark", MyRange

Try their suggestion of storing the bookmark's range into a variable ie MyRange and then calling Bookmarks.Add "mybookmark", MyRange

Dim BMRange As Range 

Set BMRange = ActiveDocument.Bookmarks("MyBookmark").Range 
BMRange.Text = "Hello world" 

ActiveDocument.Bookmarks.Add "MyBookmark", BMRange

这篇关于MS Word Interop到C#-在书签中插入多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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