通过调整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