2016-11-28 22 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

太棒了!经过一些调整,这正是我所需要的!谢谢德克。完成一些其他工作后,如果需要,可以在完成其他工作后发布完整代码。 –