如何计算和获取文档中的数字总和

时间:2014-11-26 04:25:02

标签: vba ms-word word-vba

我正在尝试创建一个Word VBA,它接受一个word文件并查找所有整数并告诉你文档中有多少个数字,并将它们总结为例如:

  "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

我已经想出如何在文档中使用元音而不是使用数字来执行此操作。我怎样才能将它变换成整数而不是元音。

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

1 个答案:

答案 0 :(得分:1)

你让它有点复杂,但重要的是,它正在发挥作用。

为了搜索数字,我建议使用Range.Find方法。完整的解决方案如下:

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

假设 - 只搜索和计算/求和整数!