如何使用VBA迭代Word中选定文本中的每个字符?

时间:2013-06-09 21:26:56

标签: vba loops ms-word selected

我正在尝试遍历循环中的选定文本(直到完成)并按顺序检索每个字符。

Word中的对象与excel中的对象有很大的不同,我可以很容易地做到这一点。任何人都有几行

  1. 捕获所选文本的长度。
  2. 遍历它并一次获得一个角色,直到我到达所选文本中的最后一个角色。

2 个答案:

答案 0 :(得分:5)

我不会对Word进行很多编码,这很令人困惑,但我认为你也会看到一些相似之处。这里有一些代码可以满足您的要求,即将所选文本中的字符数打印到即时窗口,然后打印每个字符:

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

我还投了Words个数。看起来Words包含分节符,也可能包含其他项目。

答案 1 :(得分:0)

如果您想要这样做,可以使用正则表达式将其转换为数组。

 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