在Word部分末尾插入文本_VBA

问题描述 投票:0回答:2

我有以下代码,它根据每个部分的第一段生成附录列表(跳过第 1 部分),将其添加到字符串中,然后将该字符串插入到第 1 部分的末尾。但是出于某种原因(我无法弄清楚)它将appendixList插入到第2节的开头,而不是第1节的末尾。下一节有一个分页符,位于第1节的末尾。

Sub GenerateAppendixList()
    Dim mainDoc As Document
    Dim appendixSection As section
    Dim appendixParagraph As Paragraph
    Dim appendixList As String
    Dim appendixCount As Integer
    Dim rng As Range
    
 
    ' Set reference to the main document
    Set mainDoc = ActiveDocument
    Set rng = mainDoc.Sections(1).Range

    ' Initialize the appendix count
    appendixCount = 1
 
    ' Loop through sections (excluding the main document)
    For Each appendixSection In mainDoc.Sections
        If appendixSection.Index > 1 Then
            ' Get the first paragraph in the appendix section
            Set appendixParagraph = appendixSection.Range.Paragraphs(1)
            
                appendixList = appendixList & "Appendix " & appendixCount & " - " & appendixParagraph.Range.Text '& vbCrLf
                ' Increment the appendix count
                appendixCount = appendixCount + 1
            'End If
        End If
    Next appendixSection
 
    ' Insert the formatted appendix list at the end of the Section 1
    
    rng.Collapse Direction:=wdCollapseEnd
    rng.InsertAfter appendixList
    

End Sub

我将代码更改为

rng.Collapse Direction:=wdCollapseStart
这正如我所期望的那样,并将附录列表放在章节的开头。不知道为什么
rng.Collapse Direction:=wdCollapseStart
在我的情况下不起作用。

vba ms-word
2个回答
0
投票
  • mainDoc.Sections(1).Range
    包括分节符。
    rng.Collapse Direction:=wdCollapseEnd
    将 rng 折叠到结束位置(在分节符之后,它是第 2 节的开始)。

  • 添加一行以将其移动到分节符之前

    rng.Collapse Direction:=wdCollapseEnd
    rng.MoveEnd unit:=Word.wdCharacter, Count:=-1
    rng.InsertAfter appendixList

-1
投票

您可以尝试在代码开头定义这些常量

Const wdCollapseStart As Integer = 0 Const wdCollapseEnd As Integer = 1

如果添加 选项显式 rng.Collapse Direction:=0 ' 0 对应 wdCollapseStart

没有帮助

© www.soinside.com 2019 - 2024. All rights reserved.