2012-08-22 89 views
2

這個問題聽起來很簡單,但我無法找到it.What我試圖做的是將我的光標現在的位置在MSWORD到text.My代碼的結束如下將我的光標移動到使用C#的MsWord中文本的末尾?

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#"; 
任何解決方案

輸出是

這是第一行字從C#

但是我想是這樣的

這是第一行字從C#

感謝所有

回答

3

好感謝大家的反應我似乎已經找到了一個簡單的Solution.I試圖修改哈桑的Solution.There可能是一個更容易的方法,但以現在我發現這個

object NewEndPos = rng.StoryLength-1; 
     rng = oDoc.Range(ref NewEndPos, ref NewEndPos); 
     rng.Select(); 
1

試試這個方法:

oDoc.GoTo(ref what, ref which, ref missing, ref missing); 
+0

它似乎沒有工作。 – Rohit

2
rng= oDoc.Range(ref Endpos, ref Endpos); 
rng.Select(); 
2

Similar question - Position cursor at start/end of Word document

這個答案進入有關whichwhat更多細節。答案是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); 

這種方法,因爲它並沒有告訴字將光標移動到最後一行略有不同,但最後文檔,百分比我會必須假定爲100.這將是單行文檔中行的結尾,但如果光標位於第一行(在開始處),並且我們告訴Word轉到最後一行,則不會發生任何事情:我們是已經在那裏,開始最後一行

2

這個怎麼樣?這與按Ctrl-Shift-End相同。請注意0​​是單詞應用程序,而不是文檔。假設已經選擇了正確的活動文檔。

word.Selection.EndKey(WdUnits.wdStory); 
相關問題