2016-11-28 25 views
0

我從我的VB窗口打開一個Word文檔,然後形成從應用幾個文本框添加文本。我需要將這段文字每次都放到文檔的開頭,而不是最後。已經在網上搜索了幾個小時,似乎無法找到解決辦法!我設法找到WdGoToDirection.wdGoToFirst,但不知道如何處理它。任何指導都是一種幫助。獲取到Word文檔的頂部在VB.net

 Dim oWordApp As New Word.Application 
    oWordApp.Visible = True 
    Dim oDoc As Word.Document = oWordApp.Documents.Open("C:\Users\christopherm\Desktop\TestBoard.htm") 
    oDoc = oWordApp.ActiveDocument 

    Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph 
    Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph 
    Dim oBeginning As Object = WdGoToDirection.wdGoToFirst 

    oPara1 = oDoc.Content.Paragraphs.Add 
    oPara1.Range.Text = "Heading 1234" & vbCrLf 
    oPara1.Format.SpaceAfter = 0 
    oPara1.Range.Font.Bold = True 
    oPara1.Range.Font.Size = 12 
    oPara1.Range.Font.Name = "Calibri" 
    oPara1.Range.InsertParagraphAfter() 
+0

這裏有一個[答案展示瞭如何使用WdGoToDirection(http://stackoverflow.com/a/1593245/6664878) – soohoonigan

回答

0

您需要獲取指向文檔開頭的Range對象。你可以通過獲取文檔的整個範圍,然後去那個範圍的開頭:

Dim rng as Range = ActiveDocument.Range 
rng.Collapse ' collapses the range to the beginning 

rng.Text = "Heading 1234" & vbCrLf 

Dim para1 as Paragraph = rng.Paragraphs(1) 
para1.Format.SpaceAfter = 0 
' continue here ... 

如果你不是想用Document.Paragraphs.Add方法在文檔的開頭插入一個新的段落,你需要傳遞指向該位置的範圍對象:

Dim rng As Range = ActiveDocument.Range 
rng.Collapse ' range object at the beginning of the document 

' pass the range where the paragraph shall be inserted 
Dim para1 as Paragraph = ActiveDocument.Paragraphs.Add(rng) 
+0

因此,這也讓我文檔的開始,但是我使用para1.text添加的任何段落直接到底部? –

+0

@ChrisMcCarthy:請參閱我的更新以獲得澄清。 –

+0

太棒了!經過一些調整,這正是我所需要的!謝謝德克。完成一些其他工作後,如果需要,可以在完成其他工作後發佈完整代碼。 –