vba 如何遍历word文档中的每个单词 - VBA宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22711120/
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-12 02:33:15  来源:igfitidea点击:

How to loop through each word in a word document - VBA Macro

vbams-wordword-vba

提问by Kamran

I know how to get every paragraph in a word document. But I am looking for a way to loop through each word in a MS Word document.

我知道如何获取word文档中的每个段落。但我正在寻找一种方法来遍历 MS Word 文档中的每个单词。

Sub Sample()

Dim apara As Paragraph
Dim lineText As String

For Each apara In ActiveDocument.Paragraphs

     lineText = apara.Range

     'Now print the paragraph 

     Debug.Print lineText 

Next apara

End Sub

回答by Aidan

For Each sentence In ActiveDocument.StoryRanges
    For Each w In sentence.Words
        Debug.Print w
    Next
Next

回答by Marcucciboy2

Here's another, very similar solution which may be helpful for others. The accepted answer grabs truly all words in the document including header, footer, etc., whereas this answer will only grab words in the "main" area of the document.

这是另一个非常相似的解决方案,可能对其他人有帮助。接受的答案确实会抓取文档中的所有单词,包括页眉、页脚等,而此答案只会抓取文档“主要”区域中的单词。

For Each para In ActiveDocument.Paragraphs
    For Each wrd In para.Range.Words
        Debug.Print wrd
    Next wrd
Next para