2014-09-22 93 views
1

下面的代碼應該創建一個word文檔,然後生成一個目錄。 。它應該只擁有一個名爲「導言」一個項目,但我不斷收到一個錯誤說system.runtime.interopservicesCOMException‘出現「的類型的未處理的異常’使用VSTO和Word創建目錄

object oMissing = System.Reflection.Missing.Value; 
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 

//Start Word and create a new document. 
Word.Application oWord = new Word.Application(); 
Word.Document oDoc = new Word.Document(); 

oWord.Visible = true; 
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

object oTrue = true; 
object oFalce = false; 
object styleHeading2 = "Heading 2"; 
object styleHeading3 = "Heading 3"; 
oWord.Selection.Range.set_Style(ref styleHeading2); 
oWord.Selection.Range.set_Style(ref styleHeading3); 

oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel2; 
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3; 
oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText; 

object oBookMarkTOC = "Bookmark_TOC"; 

Word.Range rngTOC = oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range; <=== Error Occurs On This Line 

rngTOC.Select(); 

object oUpperHeadingLevel = "1"; 
object oLowerHeadingLevel = "3"; 
object oTOCTableID = "TableOfContents"; 
oDoc.TablesOfContents.Add(rngTOC, ref oTrue, ref oUpperHeadingLevel, ref oLowerHeadingLevel, ref oMissing, ref oTOCTableID, ref oTrue, ref oTrue, ref oMissing, ref oTrue, ref oTrue, ref oTrue); 

Word.Paragraph oIntro; 
oIntro = oDoc.Content.Paragraphs.Add(ref oMissing); 
oIntro.Range.Text = "INTRODUCTION"; 
oIntro.Range.set_Style(ref styleHeading2); 
oIntro.Range.Font.Bold = 1; 
oIntro.Range.Font.Name = "Arial"; 
oIntro.Range.Font.Size = 12; 
oIntro.Format.SpaceAfter = 15;  
oIntro.Range.InsertParagraphAfter(); 


Word.Paragraph oPara1; 
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); 
oPara1.Range.Text = "This is the paragraph after the Introduction Title."; 
oPara1.Range.set_Style(ref styleHeading2); 
oPara1.Range.Font.Bold = 0; 
oPara1.Range.Font.Name = "Arial"; 
oPara1.Range.Font.Size = 12; 
oPara1.Format.SpaceAfter = 15;  
oPara1.Range.InsertParagraphAfter(); 

//Update table of contents 
oDoc.TablesOfContents[1].Update(); 
+0

你可以看到什麼異常消息也許用一個try-catch或調試模式下運行 – Mephy 2014-09-22 23:04:28

+0

在這條線Word.Range rngTOC = oDoc.Bookmarks.get_Item(REF oBookMarkTOC).Range出現的錯誤;。 它還表示「{」收集的請求的成員不存在。「}」 – sharpiee 2014-09-22 23:07:11

+0

我不熟悉這個API,但會消息暗示「Bookmark_TOC」實際上不存在於「書籤」中? – Sam 2014-09-22 23:10:48

回答

0

此代碼對我的作品,嘗試一下:

selection.Font.Bold = 1; 
selection.TypeText("Table of Content\n"); 
TableOfContents toc = wordDoc.TablesOfContents.Add(selection.Range, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);