问题引入
用word做表时,难免会遇到反复修改行数的情况,重新编序号比较麻烦,而自带的编号功能跨行表现较差,操作也相对繁琐。
word中自带的统计功能适用性弱,做表时总是心有余力不足。
案例:在下列表中编入序号,并计算金额总数。
思路
读取需要处理的表,逐行遍历,注意word中的table,在存在合并单元格时,不能直接读取row或column。
此处使用EenKey和MoveDown来实现逐行选取。将选中的行所含文本分割成数组。读取到的文本是当前行以空格为分隔符连接的每个单元格文本的字符串。
当数组最大下标(Len函数无效)为5时,且第5列含有数值时,即为需要处理的行。
编号增加1,金额累加,跳转至下一行……
表格遍历完毕,将累计金额写入表格下方。
效果
具体实现
Sub 添加序号并合计()
'
' 添加序号并合计 宏
'
' 快捷键 Ctrl+T
Dim tb As Table, idx As Integer, max_row As Integer, max_col As Integer
Dim r As Integer, c As Integer, current_range, arr As Variant
Dim num As Integer, amount As Integer, temp As String
Application.ScreenUpdating = False
Set tb = ThisDocument.Tables(1)
r = tb.Rows.Count
c = tb.Columns.Count
tb.Cell(1, 1).Select
For idx = 1 To r
Selection.EndKey unit:=wdRow, Extend:=True
Set current_range = Selection.Range
arr = Split(current_range, "")
If UBound(arr) = 5 Then
temp0 = Replace(arr(0), Chr(13), "")
temp4 = Replace(arr(4), Chr(13), "")
If (temp0 = "" Or IsNumeric(temp0)) And IsNumeric(temp4) Then
num = num + 1
amount = amount + Int(temp4)
tb.Cell(idx, 1).Range.Text = num
End If
End If
Selection.MoveDown
Next
Selection.EndKey unit:=wdLine, Extend:=True
Selection.Range.Text = "合计:" & amount & "元" & vbCrLf
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Application.ScreenUpdating = True
End Sub