如何在 VBA 脚本中删除 MS Word 表格行中的最后一段

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

我正在尝试编写一个 VBA 脚本,该脚本可以对 Microsoft Word 表行中的所有 2 级多列表项进行排序。我正在使用最新的 MS Word 版本 (Office 365)。

我几乎做对了,但我的脚本重新插入了行,但添加了一个额外的列表项。我设法从最后一段(最后一行)中删除列表项编号,但我似乎无法删除该段落本身。

我尝试选择最后一段并删除(这会删除该行的全部内容),我尝试过

para.Range.Delete
- 这似乎没有做任何事情。

Sub Func()
    Dim tbl As Table
    Dim curRow As Row
    Dim para As Paragraph
    Dim paras() As String
    Dim cnt As Integer
    Dim i As Integer, j As Integer
    Dim temp As String

    If Not Selection Is Nothing And Selection.Tables.Count > 0 Then
        Set tbl = Selection.Tables(1)
        Set curRow = Selection.Rows(1)
    Else
        MsgBox "Please place the cursor inside a table."
        Exit Sub
    End If

    ' Count the number of list level 2 items
    cnt = 0
    For Each para In curRow.Range.Paragraphs
        If para.Range.ListFormat.ListLevelNumber = 2 Then
            cnt = cnt + 1
        End If
    Next para
    
    ' Collect the items in an array and remove them from the list
    ReDim paras(1 To cnt)
    cnt = 0
    For Each para In curRow.Range.Paragraphs
        If para.Range.ListFormat.ListLevelNumber = 2 Then
            cnt = cnt + 1
            paras(cnt) = para.Range.Text
            para.Range.Text = ""
        End If
    Next para

    ' Shuffle the array
    Randomize
    For i = 1 To cnt - 1
        j = Int((cnt - i + 1) * Rnd + i)
        temp = paras(i)
        paras(i) = paras(j)
        paras(j) = temp
    Next i

    ' Insert shuffled items back as level 2 list entries
    For i = 1 To cnt
        curRow.Range.InsertAfter paras(i)
    Next i
    
    Set para = curRow.Range.Paragraphs(curRow.Range.Paragraphs.Count - 1)
    para.Range.ListFormat.RemoveNumbers
    ' para.Range.Delete - doesn't do anything
    
End Sub
vba ms-word
1个回答
0
投票

请尝试

    Set para = curRow.Range.Paragraphs(curRow.Range.Paragraphs.Count - 1)
    para.Range.ListFormat.RemoveNumbers
    para.Range.Characters.Last.Previous.Delete  ' ** add ** '

如果您的表格布局不适用于您的文件,请分享带有示例文本的表格布局。

enter image description here

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