首页 > 解决方案 > 如何在 vb.net 的 word 文档中指定插入点?

问题描述

我正在构建一个应用程序来编辑现有的 Word 文档。

代码应删除第二页上的一个段落并将其替换为由字符串变量“Direct_introduction”标识的另一个段落。

问题是文本被插入到文档的末尾,即使指定了段落的数量,我也无法将其插入到其他任何地方。

If DirectRB.Checked Then
        'introRange.Delete()
        'Dim ODirect_intropara As Word.Paragraph = oDoc.Paragraphs.Add()
        'ODirect_intropara.Range.Font.Name = "Arial Narrow"
        'ODirect_intropara.Range.Font.Bold = CInt(False)
        'ODirect_intropara.Range.Font.Size = 11
        'ODirect_intropara.Format.SpaceAfter = 0
        'ODirect_intropara.Range.Text = Direct_introduction
        'ODirect_intropara.Range.ParagraphFormat.Alignment = 
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft
        'ODirect_intropara.Range.InsertParagraphAfter()

        introPara = oDoc.Content.Paragraphs.Add
        introPara.Range.Text = Direct_introduction
        introPara.Range.Font.Bold = True
        introPara.Format.SpaceAfter = 24    '24 pt spacing after 
paragraph.
        introPara.Range.InsertParagraphAfter()
        Rng = oDoc.Range(oDoc.Range.Characters.Count - 1, 
oDoc.Range.Characters.Count)
        Rng.InsertAfter(vbCrLf & "More text inserted using the range 
object")


    ElseIf PartnerRB.Checked Then
        MessageBox.Show("you checked Partner")

    End If

标签: vb.netwinformsms-word

解决方案


对“Direct_introduction”执行查找,如果找到,则在当前位置插入。例如(在 VBA 中):

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "Direct_introduction"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = True
    .MatchWildcards = False
    .Execute
  End With
  If .Find.Found = True Then
    .Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa." & vbCr & _
      "Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna." & vbCr & _
      " Nunc viverra imperdiet enim." & vbCr & _
      "Fusce est. Vivamus a tellus."
  End If
End With
Application.ScreenUpdating = True
End Sub

推荐阅读