VBA-Word更改单词的概念(a.b是一个或两个单词)

时间:2018-10-31 15:57:13

标签: vba ms-word

我有一个问题:我想要一个WORD文档的单词数组,该单词数组大于29个字符且小于40个字符。我是通过VBA来实现的:

Sub function()

    Dim arr(1000) As String
    counter = 0

    For Each sentence In ActiveDocument.StoryRanges
        For Each w In sentence.Words
            If Len(w) > 28 And Len(w) < 40 Then
                arr(counter) = w
                counter = counter + 1
            End If
        Next
    Next

End Sub

问题是我希望所有带有char'_'的单词都被当作一个单词。例如:“ Adrian_link_mart”是一个单词,而不是3:像这样将被视为“ Adrian”,“ link”和“ mart”

感谢您的帮助,阿德里安

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助。您会在下面看到一些皱纹。

Option explicit

Sub test()

' Use a collection rather than an array as we don't need
' to know the size in advance
Dim word_array              As Collection
' Word doesn't actually have a  'word' object. Probably because
' that clashes with Word the application.  So instead of Word.Word
' we are using word.range which gives us all the utility we will
' need
Dim my_word_range           As Word.Range
Dim my_range                As Word.Range

    For Each my_range In ActiveDocument.StoryRanges
        For Each my_word_range In my_range.Words
            With my_word_range
                Do While .Next(unit:=wdCharacter) = "_"
                    ' '_' is considered to be a word  by Word so we need to
                    ' count two Word words to get to the end of the next
                    ' text word IYSWIM
                    .MoveEnd unit:=wdWord, Count:=2

                Loop

                If .Characters.Count > 28 And .Characters.Count < 40 Then
                    word_array.Add Item:=.Text

                End If

            End With

        Next

    Next

End Sub

如果您是VBA的新手,那么

  1. 在每个模块顶部显式包含选项

  2. 在VBA IDE中,转到“ Tools.Option.Editor.Code设置”,并确保选中每个框。

  3. 了解如何使用F1。在VBA IDE中,将光标置于某个关键字上并按F1键将弹出该关键字的MS帮助页面