排序期间不包括最后一行

时间:2019-07-15 15:10:33

标签: vba ms-word

通过调整AddArrayName上的forloop来按递增顺序计数和填充,我无需剪切,排序或向后插入行即可解决问题。

Sub AddArrayName()
With ActiveDocument

Dim tbl As Object
Dim noOfCol As Integer
Dim i As Long
Dim j As Integer

j = cbArraySize.Value

Set tbl = .Tables(2)
    With tbl
        noOfCol = tbl.Range.Rows(1).Cells.Count
        For i = .Rows.Count To 1 Step -1
            With .Rows(i)
                If Len(.Range) = noOfCol * 2 + 2 Then 
.Cells(1).Range.InsertAfter Text:=tbArrayName.Text + " - " & j + 1
            End With
        j = j - 1
        Next i

End With
End With
End Sub

我有一个动态表,该表创建x行并根据用户输入自动填充第一个单元格。命名后,我将排除标题并对行进行排序。最后一行需要从排序中排除,因为它包含“ Notes:”。

我相信我将需要一个for循环来获取最后一行-1,但由于我是VBA的新手,并且仍在尝试学习基础知识,因此无法将其环绕在头或从哪里开始。

Sub TableSort() ActiveDocument.Tables(2).Sort ExcludeHeader:=True End Sub

这是我目前拥有的内容,分为多个单独的Sub。除了在最后一行之前插入范围之外,我都可以使用它。

Private Sub cbArraySize_Click()

If cbArraySize.Value <> 0 Then

DeleteRows
CutRow2
AddRows
AddArrayName
TableSort
InsertRow2

End If

End Sub

Sub DeleteRows()

Dim tbl As Word.Table
Dim nrRows As Long, ColToCheck As Long, i As Long
Dim cellRange As Word.Range

Set tbl = ActiveDocument.Tables(2)
nrRows = tbl.Rows.Count - 1
ColToCheck = 2

For i = nrRows To 1 Step -1
    Set cellRange = tbl.Cell(i, ColToCheck).Range
    If Len(cellRange.Text) = 2 Then
        cellRange.Rows(1).Delete
    End If
Next i

End Sub

Sub CutRow2()

With ActiveDocument

.Tables(2).Rows(2).Select
Selection.Cut
End With

End Sub 

Sub AddRows()

With ActiveDocument

.Tables(2).Rows(1).Select
Selection.InsertRowsBelow (cbArraySize.Value)

End With

End Sub

Sub AddArrayName()
With ActiveDocument

Dim tbl As Object
Dim noOfCol As Integer
Dim i As Long
Dim intcount As Integer

intcount = 1

Set tbl = .Tables(2)
    With tbl
        noOfCol = tbl.Range.Rows(1).Cells.Count
        For i = .Rows.Count To 1 Step -1
            With .Rows(i)
                If Len(.Range) = noOfCol * 2 + 2 Then 
.Cells(1).Range.InsertAfter Text:=tbArrayName.Text + " - " & intcount
            intcount = intcount + 1
            End With
        Next i
End With
End With
End Sub

然后我对不包含标题的表进行排序。

InsertRow2()

Dim mytable As Object
Set mytable = ActiveDocument.Tables(2)

mytable.Rows(mytable.Rows.Count).Range.Paste

End Sub

在InsertRow2()子例程之后,它将范围插入到最后一行之前。

表格示例:End Table Result I am looking for

它的实际作用:Actual Table Result

1 个答案:

答案 0 :(得分:0)

VBA的经验法则:如果您不能以最终用户的身份来做,那么VBA也可能做不到。 Word的内置Sort命令只能排除标题行,而不能排除表末尾的行。

据我所知,解决此问题的唯一方法是将最后一行拆分为一个单独的表。这将在其间放置一个段落标记,但可以使用“隐藏”字体格式对其进行格式化,以使两个表看起来像一个表。如此一来,您就可以对表格进行排序,而无需添加“注释”,如下所示。

enter image description here