gpt4 book ai didi

vba - 使用Word VBA删除最后一个列表项

转载 作者:行者123 更新时间:2023-12-04 20:19:01 24 4
gpt4 key购买 nike

我试图从带有VBA的Word中的项目符号列表中删除最后一个项目符号/项目。

可以使用以下代码获取空项目,但我不知道如何删除此项目:

For Each List In ActiveDocument.ListParagraphs
If Len(List.Range.Text = 2) Then
'Delete this list Item
End If
Next


这是列表的示例:


项目1
项目2
项目3



我已经尝试过通过Range.Text.Select选择项目,但是那没有用。

欢迎任何建议,谢谢。

编辑:

问题是删除整个列表项,包括列表项目符号。 list.Range.Delete不起作用,并且看起来宏甚至崩溃了。

即使文档中有多次出现,该消息框也只会出现一次,如果删除 list.Range.Delete,则对于每个空项目,该消息框都会出现一次。

Dim list As Paragraph

For Each list In ActiveDocument.ListParagraphs
MsgBox Len(list.Range.Text)
If Len(list.Range.Text) = 2 Then
MsgBox "DELETE"
list.Range.Delete
End If
Next

最佳答案

对于空白列表段落,List.Range.Text = 2不会是true。是1

Dim list As Paragraph

For Each list In ActiveDocument.ListParagraphs
If Len(Trim$(list.Range.Text)) = 1 Then
list.Range.Delete
End If
Next


编辑: ActiveDocumentTrim$在注释中建议。



问题在于,表单元格中的最后一个段落的最后一个字符具有单元格结束标记,因此可能无法删除。

通用解决方案是始终在检查其长度之前从段落中删除最后一个字符。由于应删除的段落的长度为零,因此我们可以将其“向左”删除(就像按下了退格键一样),这样既保留了单元格结束标记,也适用于不在表格中的段落。但是,如果删除的段落不为空,则这将不起作用:

Dim p As Paragraph

For Each p In ActiveDocument.ListParagraphs
Dim range_to_examine As Range
Set range_to_examine = p.Range

If range_to_examine.End = range_to_examine.Start + 1 Then
range_to_examine.Collapse wdCollapseStart
range_to_examine.Delete wdCharacter, -1
End If
Next

关于vba - 使用Word VBA删除最后一个列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8564329/

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