C# 使用VSTO和Word创建目录

C# 使用VSTO和Word创建目录,c#,ms-word,vsto,C#,Ms Word,Vsto,下面的代码应该创建一个word文档,然后生成一个目录。它应该只有一个名为“INTRODUCTION”的项,但我一直收到一个错误,说发生了“system.runtime.interopservicesCOMException”类型的“未处理的异常” object omising=System.Reflection.Missing.Value; object oEndOfDoc=“\\endofdoc”/*\endofdoc是一个预定义的书签*/ //启动Word并创建新文档。 Word.Appli

下面的代码应该创建一个word文档,然后生成一个目录。它应该只有一个名为“INTRODUCTION”的项,但我一直收到一个错误,说发生了“system.runtime.interopservicesCOMException”类型的“未处理的异常”

object omising=System.Reflection.Missing.Value;
object oEndOfDoc=“\\endofdoc”/*\endofdoc是一个预定义的书签*/
//启动Word并创建新文档。
Word.Application oWord=新单词.Application();
Word.Document oDoc=新的Word.Document();
可见=真;
oDoc=oWord.Documents.Add(引用删除、引用删除、引用删除、引用删除);
object oTrue=true;
ALCE的对象=false;
object styleHeading2=“Heading 2”;
object styleHeading3=“Heading 3”;
oWord.Selection.Range.set_样式(参考样式标题2);
oWord.Selection.Range.set_样式(参考样式标题3);
oWord.Selection.parations.OutlineLevel=Word.WdOutlineLevel.wdOutlineLevel2;
oWord.Selection.parations.OutlineLevel=Word.WdOutlineLevel.wdOutlineLevel3;
oWord.Selection.parations.OutlineLevel=Word.WdOutlineLevel.wdOutlineLevelBodyText;
object oBookMarkTOC=“Bookmark\u TOC”;

Word.Range rngTOC=oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range;这段代码适合我,试试看:

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

你能看到异常消息是什么吗?可能使用try-catch或在调试模式下运行。错误发生在这一行Word.Range rngTOC=oDoc.Bookmarks.get_Item(ref oBookMarkTOC).Range;它还说“{”请求的集合成员不存在。“}”我不熟悉这个API,但该消息是否暗示“Bookmark_TOC”“实际上不存在于
书签中”
?此外,它可能会帮助您将该行分解为多个语句,每项操作在一行上(一个用于
.Bookmarks
,一个用于
.get\u Item
,一个用于
.Range
)。这会让你更清楚地知道是哪个操作引发了异常。请给你的问题一个有意义的标题。目前它的范围太广了。
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);