MS Word Interop to C# - Inserting multiple files at a bookmark

风格不统一 提交于 2019-12-24 10:48:12

问题


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.

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.

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


回答1:


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.

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


来源:https://stackoverflow.com/questions/15396301/ms-word-interop-to-c-sharp-inserting-multiple-files-at-a-bookmark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!