0
votes

I used the following code in word-VBA. But when I executed it on a selected paragraph, it gives Run-time error-5854 "String parameter too long". It works fine for small paragraphs. Please help.

Code:

Sub Count_of_words()
'
' Count Macro
'
'

Dim WrdArray() As String
Dim i As Integer

WrdArray() = Split(Selection, ".") 'Change with ; if required
'MsgBox ("length: " & UBound(WrdArray))

For i = 0 To UBound(WrdArray)

    If (Number_of_Words(WrdArray(i))) > "20" Then

        '****Set search parameters***************

        Selection.Find.Text = WrdArray(i)
        Selection.Find.Execute
        Selection.Collapse wdCollapseStart
        Selection.Select
        Selection.MoveRight wdCharacter, Len(WrdArray(i)) + 1, True
        Selection.Range.Font.Color = RGB(255, 0, 0)

        Selection.Collapse wdCollapseEnd

        '****************************************

    End If
Next i

End Sub

Function Number_of_Words(Text_String As String) As Integer
'Function counts the number of words in a string
'by looking at each character and seeing whether it is a space or not
Number_of_Words = 1
Dim String_Length As Integer
Dim Current_Character As Integer
Dim actualText As String

actualText = Trim(Text_String)
String_Length = Len(actualText)

For Current_Character = 1 To String_Length

    If (Mid(actualText, Current_Character, 1)) = " " Then
        Number_of_Words = Number_of_Words + 1
    End If

Next Current_Character
'MsgBox ("Number_of_Words: " & Number_of_Words)
End Function
2
If (Number_of_Words(WrdArray(i))) > "20") can't be right because Number_of_Words() returns an int.Paul Ogilvie
It works fine for length of "wrdArray(I)" < 255. It's giving error only if "wrdArrar( I)" >255.Pankaj Kumar

2 Answers

0
votes

You haven't told us where the error occurrs.

Doing some research on the net, it seems that the Find and Replace functionality is limited to strings of 255 characters.

So it seems the error occurrs when calling this functionality, not when passing your string to Number_of_Words().

0
votes

That code seems very wrong as it assumes that all sentences are separated by "." and that all words are separated by one " ". I think it should be something like this:

Dim s As Range
For Each s In Selection.Sentences
    If s.Words.Count > 20 Then s.Font.Color = wdColorRed
Next