VBA实例2 Word表格编号及金额统计

问题引入

用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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值