使用数组与EXCEL的好处是,还可以进行更多对此数据的计算与统计。 以下方法,是简单的累加与平均值计算,亦供参考: '* +++++++++++++++++++++++++++++
'* Created By I Love You_Word!@ExcelHome 2005-4-23 07:29:51
'仅测试于System: Windows NT Word: 10.0 Language: 2052
'^The Code CopyIn [ThisDocument-ThisDocument]^'
'* -----------------------------Option Explicit
Sub ExampleToEasy()
Dim i As Integer, RowsCount As Integer, N As Integer, M As Integer
Dim SumValue1 As Double, SumValue2 As Double
Dim TotalValue1 As Double, TotalValue2 As Double, strName As String
Application.ScreenUpdating = False '关闭屏幕更新
With ActiveDocument
RowsCount = .Tables(1).Rows.Count '取得表格总行数
For i = 2 To RowsCount - 1 '从第二行开始到最后第二行
N = N + 1 '累计数
'数据累加
SumValue1 = SumValue1 + VBA.Val(.Range(.Tables(1).Cell(i, 8).Range.Start, .Tables(1).Cell(i, 8).Range.End - 1))
SumValue2 = SumValue2 + VBA.Val(.Range(.Tables(1).Cell(i, 9).Range.Start, .Tables(1).Cell(i, 9).Range.End - 1))
TotalValue1 = TotalValue1 + VBA.Val(.Range(.Tables(1).Cell(i, 8).Range.Start, .Tables(1).Cell(i, 8).Range.End - 1))
TotalValue2 = TotalValue2 + VBA.Val(.Range(.Tables(1).Cell(i, 9).Range.Start, .Tables(1).Cell(i, 9).Range.End - 1))
If .Tables(1).Cell(i + 1, 2).Range <> .Tables(1).Cell(i, 2).Range Then
'取得人名
strName = .Range(.Tables(1).Cell(i, 2).Range.Start, .Tables(1).Cell(i, 2).Range.End - 1)
'插入平均价格和合计金额
.Content.InsertAfter Chr(13) & strName & "平均价格:" & SumValue1 / N & "合计金额" & SumValue2 & Chr(13)
N = 0: SumValue1 = 0: SumValue2 = 0 '初始化三变量
End If
Next
'在文档最后插入平均价格与累计金额
.Content.InsertAfter Chr(13) & "平均价格:" & TotalValue1 / (RowsCount - 2) & "累计金额" & TotalValue2
End With
Application.ScreenUpdating = True '恢复屏幕更新
End Sub
'---------------------- |