hue manny
hue manny

Reputation: 247

How to count and get the sum of numbers in a document

I am trying to create a Word VBA that takes a word file and finds all the integers and tells you how many numbers are in the document and also sums them up for example:

  "Today was a good day it is around 4 pm and I see about 7 birds
   I  have to be home at around 6"

   There are 3 numbers in this document 
   The sum of these numbers is 17

I have figured out how to do this with vowels in the document but not with numbers. How can I transform it so it can do integers and not vowels.

Option Explicit
Public Sub CountVowels()

     Dim docText As String
     Dim docCopy As String 

    Const VOWEL_STRING As String =  “aeiou”
    Const Max_Vowels As Integer =  5

    Dim vowelCounts(Max_Vowels) As Long

    Dim i As Long 
    Dim totalVowels As Long
    Dim ch As String *1
    Dim k As Integer
    Dim outputStr As String

    docText = ActiveDocument.Content.Text

    docCopy = LCase(docText)

For i = 1 To Len(docCopy)
    ch = Mid(docCopy, i, 1)
    If isVowel(ch) Then

        totalVowels = totalVowels +1
        k = Instr(VOWEL_STRING, ch)

        vowelCounts(k) = vowelCounts(k) +1
    End If
Next i 
    outputStr = vbCr & vbCr & “The counts of each vowel are:”
    outputStr = outputStr & vbCr & vbCr

    For i = 1 To MAX_VOWELS
        outputStr = outputStr & Mid(VOWEL_STRING, i , 1) & ”:   “ &
                   vowelCounts(i) & vbCr
    Next i

    ActiveDocument.Content.Text = docText & outputStr

End Sub

Upvotes: 1

Views: 133

Answers (1)

Kazimierz Jawor
Kazimierz Jawor

Reputation: 19067

You made it a bit complicated but, which is important, it is working.

For searching numbers I suggest to use Range.Find method. Complete solution could be as follows:

Sub SearchNumbers()

Dim Counter As Long
Dim Total As Long



    With Selection.Find
        .Text = "[0-9]{1;}"     'IMPORTANT!! if not working try to use , instead of ; in your environment
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With

    Do While Selection.Find.Execute
        Counter = Counter + 1
        Total = Total + Selection

    Loop
    MsgBox "There are " & Counter & " numbers in this document. " & vbNewLine & _
            "The sum of these numbers is " & Total

End Sub

Assumptions- searching and counting/summing only integers!

Upvotes: 1

Related Questions