2
votes

I'm trying to iterate through selected text within a loop (until done) and retrieve each character in order.

The objects within Word seem much different than in excel where I can do this quite easily. Anyone have a few lines to

  1. capture the length of the selected text.
  2. iterate through it and get a each character one at a time until I get to the last character in the selected text.
2

2 Answers

5
votes

I don't code Word a lot, and it is confusing, but I think you'll see some similarities too. Here's some code that does what you asked for, i.e., prints the count of characters in the selected text to the immediate window, and then prints each character:

Sub CountWordStuff()
Dim char As Range

With Selection
    Debug.Print "Character count: "; .Characters.Count
    Debug.Print "Words - kind of: "; .Words.Count; ""

    For Each char In Selection.Characters
        Debug.Print char.Characters(1)
    Next char
End With
End Sub

I also threw in a Words count. It looks like Words includes paragraph breaks, and probably other items, as well.

0
votes

You could use Regular Expressions to turn it into array if that's what you are wanting to do.

 Function TextIntoObject(InputString As String) As Object
'Reference set to Microsoft VBScript Regular Expressions 5.5
Dim RegExp As New RegExp
RegExp.Pattern = "."
RegExp.Global = True
Set TextIntoObject = RegExp.Execute(InputString)


End Function

Sub TestFunction()
Dim i As Integer
Dim x As Integer
Dim SampleText As String
SampleText = "This is the text I want to use"
x = TextIntoObject(SampleText).Count
MsgBox "The length of my text is " & x
For x = 0 To x - 1
    MsgBox TextIntoObject(SampleText)(x)
Next

End Sub