类似问题 - 将光标定位在 Word 文档的开头/结尾
该答案更详细地介绍了which
和what
。答案在 c# 和 vb 之间混杂在一起,因此我在此处提供了另一个答案,它使用稍微不同的方法转到文档的最后一部分。
我的两分钱:
//vb does this kind of thing for them
//but in c# we need an object we can pretend is null
object oMissing = System.Reflection.Missing.Value;
//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc; //whenever i read this i think 'hodor'
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
object StartPos = 0;
object Endpos = 1;
Microsoft.Office.Interop.Word.Range rng = oDoc.Range(ref StartPos, ref Endpos);
rng.Text = "This is first line Word from C#";
//object what = Word.WdGoToItem.wdGoToLine;
//I couldn't get wdGoToLine to work but wdGoToPercent was happy
object what = Word.WdGoToItem.wdGoToPercent;
object which = Word.WdGoToDirection.wdGoToLast;
oWord.Selection.GoTo(ref what, ref which, oMissing, oMissing);
这种方法略有不同,它不会告诉 word 将光标移动到最后一行,而是文档的最后一个百分比,我必须假设为 100。那将是一行的结尾-line 文档,但是如果光标在第一行(在开头)并且我们告诉 Word 转到最后一行,则什么也不会发生:我们已经在最后一行的开头。