gpt4 book ai didi

vba - 删除 Word VBA 中的最后一部分而不覆盖前一个标题

转载 作者:行者123 更新时间:2023-12-02 16:59:33 24 4
gpt4 key购买 nike

我在搜索问题时发现了以下代码。此代码的问题在于它会将倒数第二节的页眉(和页脚,尽管我只需要保留页眉)覆盖为最后一节的页眉,这是 Word 的默认(奇怪)行为。

在 VBA 中是否有解决此问题的方法?

这是有固有错误的代码:

Sub DeleteLastSection()
'Deletes last section of a document including
'the section break
Dim doc As Document
Dim rng As Range
Dim ctr As Integer
Set doc = ActiveDocument
ctr = doc.Sections.Count
Set rng = doc.Sections(ctr).Range
Dim myheader As HeaderFooter
If ctr > 1 Then
With rng
.Select
.MoveStart Unit:=wdCharacter, Count:=-1
.Delete
End With
End If
End Sub

注意:代码正在删除最后一部分的整个范围,这是必需的行为。 Word 默认行为的固有问题是我需要在 VBA 代码中解决的问题。人们可以找到复杂的手动过程来避免它,但我需要一种简单的代码方法。

最佳答案

这里的问题在于分节符携带的是分节信息。如果删除它,最后一节将成为前一节的一部分。我在下面使用的技巧是创建一个连续的分节符而不是分页符,然后执行所有其余操作:

Sub DeleteLastSection()
'Deletes last section of a document including
'the section break
Dim doc As Document
Dim rng As Range
Dim NewEndOfDocument As Range
Dim ctr As Integer
Set doc = ActiveDocument
ctr = doc.Sections.Count
Set rng = doc.Sections(ctr).Range

If ctr > 1 Then
' Create a section break at the end of the second to last section
Set NewEndOfDocument = doc.Sections(ctr - 1).Range
NewEndOfDocument.EndOf wdSection, wdMove
doc.Sections.Add NewEndOfDocument, wdSectionContinuous

With rng
.Select
.MoveStart Unit:=wdCharacter, Count:=-1
.Delete
End With
End If
End Sub

关于vba - 删除 Word VBA 中的最后一部分而不覆盖前一个标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com