Search code examples
vbams-wordsentencecitations

Find long sentences where there is no space between the period and endnote citations (superscripts)


I have a loop that looks for sentences over 30 words long. If found, it adds a comment box to the selected sentence. It worked in testing. Then I added some test endnote citations and it fails to find the long sentences.

It fails when there is no space between the period and the citation superscript. There is not supposed to be a space between the period and the citation, per the style guide I have to follow at work.

This related Stack thread discusses the need for a space after a period to delineate the end of a sentence. I assume the space must be directly after the period, because I have spaces in my citations like this 1, 2, 3

How can I find instances of period+superscript (with no space like this --> This is a sentence.1, 2, 3) and add a space? Ideally I would like this to happen within the below loop so I can remove the space after the comment gets added.

Sub Comment_on_Long_Sentences ()

Dim iWords as Integer

iWords = 0

For Each MySent in ActiveDocument.Sentences

    If MySent.Words.Count > iWords Then

        MySent.Select

        'find and delete space

        ActiveDocument.Comments.Add Range:= Selection.Range, Text:= "Long Sentence: " & iWords & " words"

        'put the space back

    End if

Next MySent

End Sub

Solution

  • There appears to be issues in VBA when trying to access Sentences that end with a superscript character. Your code also has problems with non-declared variables, so I have no idea how it ever worked for you in the first place.

    Try this following VBA routine, it works in my environment. Also notice the special handling that I found is required for 1st sentences in paragraphs and when that sentence ends with a superscript character.

    Sub Comment_on_Long_Sentences()
        Dim doc As word.Document, rng As word.Range, para As word.Paragraph
        Dim i As Long
    
        Set doc = ActiveDocument
        For Each para In doc.Paragraphs
            Debug.Print para.Range.Sentences.Count
            For i = 1 To para.Range.Sentences.Count
                Set rng = para.Range.Sentences(i)
                If i = 1 And rng.Characters.First.Font.Superscript = True Then
                    rng.MoveStart word.WdUnits.wdSentence, Count:=-1
                End If
                If rng.words.Count > 30 Then
                    doc.Comments.Add Range:=rng, Text:="Long Sentence: " & rng.words.Count & " words"
                End If
            Next
        Next
    End Sub