Count instances of a specific word and return new document up to up to a range (based on that word)

13 Views Asked by At

I don't have problem returning the total word count, or splitting a document into a new one based on word count but this is proving more difficult.

I want to count the instances of 'CHAPTER' (stage one) and then as a separate function return a new document.

To count instances I have tried...

Public Function ReturnWordPages(FileName As String) As Integer
Try
        Dim WordApp As ApplicationClass = New ApplicationClass()
    Dim vFilename As Object = FileName
    Dim [readonly] As Object = False
    Dim isVisible As Object = False
    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim wDoc As Document = WordApp.Documents.Open(vFilename, oMissing, [readonly], oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, isVisible)
   
    Dim vRange = wDoc.Range
    Dim TotalChapters As Integer = 0
    vRange.Collapse(WdCollapseDirection.wdCollapseStart)
    While True
        vRange.Find.ClearFormatting()
        vRange.Find.Text = "CHAPTER"
        vRange.Find.Forward = True
        vRange.Find.Wrap = WdFindWrap.wdFindStop
        vRange.Find.Format = False
        vRange.Find.MatchCase = True
        vRange.Find.MatchWholeWord = True
        vRange.Find.MatchWildcards = False
        vRange.Find.Execute()
        If Not vRange.Find.Found Then Exit While
        TotalChapters += 1
        vRange.Collapse(WdCollapseDirection.wdCollapseEnd)
    End While

    WordApp.Quit()
    WordApp = Nothing
    Return TotalChapters


Catch ex As Exception
    EmailError(ex)
    Return 0
End Try
End Function

But it always returns zero. Any pointers?

0

There are 0 best solutions below