我正在尝试编写一个 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