Thread: [Solved] Sum validation in ms word..
View Single Post
 
Old 04-18-2020, 02:27 PM
macropod's Avatar
macropod macropod is offline Windows 7 64bit Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 21,963
macropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond repute
Default

Try the following macro. It loops through all tables in the document, testing whether cells in anything other than the top row & left column are numeric, highlighting them if they aren't. If just one cell other than the total in a column exhibits an error, a new value is calculated. Pink highlight is used for non-numeric entries, green for repaired entries and yellow for totals where a repair can't be made. That should do most of the work for you, leaving you with relatively few things to check.
Code:
Sub Demo()
Dim Tbl As Table, r As Long, c As Long, x As Long, y As Long, Str As String, Val As Double
For Each Tbl In ActiveDocument.Tables
  With Tbl
    For c = 2 To .Columns.Count
      Val = 0: x = 0
      For r = 2 To .Rows.Count - 1
        With .Cell(r, c).Range
          Str = Trim(Split(.Text, vbCr)(0))
          .Text = Str
          If IsNumeric(Str) Then
            Val = Val + CDbl(Str)
          Else
            .HighlightColorIndex = wdPink
            x = x + 1: y = r
          End If
        End With
      Next
      With .Cell(r + 1, c).Range
        Str = Trim(Split(.Text, vbCr)(0))
        .Text = Str
        If IsNumeric(Str) Then
          If Val <> CDbl(Str) Then
            If x = 1 Then
              With Tbl.Cell(y, c).Range
                .Text = Format(CDbl(Str) - Val, "#,##0.00")
                .HighlightColorIndex = wdBrightGreen
              End With
            Else
              .HighlightColorIndex = wdYellow
            End If
          End If
        Else
          If Val <> 0 Then .HighlightColorIndex = wdYellow
        End If
      End With
    Next
  End With
Next
End Sub
__________________
Cheers,
Paul Edstein
[Fmr MS MVP - Word]
Reply With Quote