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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17014351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:33:03  来源:igfitidea点击:

How do you iterate each character within selected text in Word using VBA?

vbaloopsms-wordselected

提问by user2469149

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

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

  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.
  1. 捕获所选文本的长度。
  2. 遍历它并一次获取一个字符,直到到达所选文本中的最后一个字符。

回答by Doug Glancy

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:

我不经常编写 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

I also threw in a Wordscount. It looks like Wordsincludes paragraph breaks, and probably other items, as well.

我也算了一笔Words账。它看起来Words包括段落分隔符,可能还有其他项目。

回答by dennythecoder

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