Sum column in word table

YasserKhalil
PlatinumLounger
Posts: 4662
Joined: 31 Aug 2016, 09:02

Sum column in word table

Post by YasserKhalil »

Hello everyone

I have multiple word documents and each document has some tables which I need to put a sum formula
I could use AutoSum feature but this enables me to sum only one row. How can I apply the sum formula along all the rows of the table in the word document?

YasserKhalil
PlatinumLounger
Posts: 4662
Joined: 31 Aug 2016, 09:02

Re: Sum column in word table

Post by YasserKhalil »

I tried such a code

Code: Select all

    Dim tbl As Word.Table
    Dim col As Word.Row
    Dim runningSum As Double
    Dim cel As Word.Cell
    Dim celContent As String

    Set tbl = ActiveDocument.Tables(1)
    Dim i As Long
    For i = 2 To tbl.Rows.Count
    Set col = tbl.Rows(i)
    runningSum = 0
Dim cnt As Long
cnt = 0
    For Each cel In col.Cells
    cnt = cnt + 1
    If cnt = 1 Or cnt = 2 Then GoTo Skipper
        celContent = Mid(cel.Range.Text, 1, Len(cel.Range.Text) - 1)
        'celContent = cel.Range.Text
        If IsNumeric(celContent) Then
            runningSum = runningSum + CDbl(celContent)
        End If
Skipper:
    Next
    Debug.Print runningSum
    Next i
How can I post the result in the last column of each row?

YasserKhalil
PlatinumLounger
Posts: 4662
Joined: 31 Aug 2016, 09:02

Re: Sum column in word table

Post by YasserKhalil »

I could solve it but I welcome any other ideas

Code: Select all

Sub SUM_Each_Row_In_Word_Table()
    Dim tbl As Word.Table, rw As Word.Row, cel As Word.Cell, celContent As String, runningSum As Double, cols As Long, i As Long, cnt As Long
    For Each tbl In ActiveDocument.Tables
        cols = tbl.Columns.Count
        For i = 2 To tbl.Rows.Count
            Set rw = tbl.Rows(i)
            runningSum = 0: cnt = 0
            For Each cel In rw.Cells
                cnt = cnt + 1
                If cnt = 1 Or cnt = 2 Then GoTo Skipper
                If cnt = cols Then cel.Range.Text = runningSum: GoTo nxtRow
                celContent = Mid(cel.Range.Text, 1, Len(cel.Range.Text) - 1)
                If IsNumeric(celContent) Then runningSum = runningSum + CDbl(celContent)
Skipper:
            Next cel
nxtRow:
        Next i
    Next tbl
End Sub