我有一段代码可以循环遍历文档,然后将每个单词存储在字典中。字典中的每个键都是“单词”本身,与该键对应的每个字典项都是一个数组,其中包含该单词的(起始和结束)范围。如果单词出现多次,我们只需将新范围添加到字典项数组中,这意味着该项数组已成为一个包含单词实例“n”的范围的子数组的数组,如图所示。
问题是:每个字典项中的第一个子数组被分成两个数组,一个存储起始范围,一个存储结束范围,如监视窗口所示。我只需要一个数组来存储这些值,后面的子数组都可以。
当我涉及到高亮代码时,我希望能够根据用户输入高亮显示出现“x”次数的单词。然而,在上述问题存在的情况下,每个单词似乎都会显示出现“x+1”次,例如,如果一个单词出现了“3”次,那么该单词的项数将显示为“4”次,这是错误的,我可以通过减去(1)来修复它,但我不想这样做。是的,我可以编写一段代码,使用“find”方法来突出显示具有“x”频率的单词。
这里是完整的代码
Sub MapWordsAndHighlight()
Dim WordsDict As Object
'a dict. to hold words and their range values
Set WordsDict = CreateObject("Scripting.Dictionary")
'an object representing each word in the cgosen document
Dim WordObject As Variant
'a temp. arr. to hold range values while adding new ones
Dim TmpRangeArrOfDupWords() As Variant
'the new upper bound of the tmp arr to recive the new values
Dim TmpArrayNewUpperBound As Long
'string that represents each words in the chosen document
Dim SingleWord As String
Dim i As Long
'loop through each word in current document
For Each WordObject In ActiveDocument.Range.Words
'remove the surrounding spaces and store the word string
SingleWord = Trim(WordObject.Text)
'skip single characters
If Len(SingleWord) > 1 Then
'check if the word is not stored previously in the dict
If Not WordsDict.Exists(SingleWord) Then
WordsDict.Add Key:=SingleWord, Item:=GetWordRangeArray(WordObject)
Else
'dump old range vlaues into tmp array
TmpRangeArrOfDupWords = WordsDict(SingleWord)
'make a new place in tmp arr for new ranges
TmpArrayNewUpperBound = UBound(TmpRangeArrOfDupWords) + 1
'expand the tmp array
ReDim Preserve TmpRangeArrOfDupWords(1 To TmpArrayNewUpperBound)
'store new ranges at the last placein tmp arr
TmpRangeArrOfDupWords(TmpArrayNewUpperBound) = GetWordRangeArray(WordObject)
WordsDict(SingleWord) = TmpRangeArrOfDupWords
Erase TmpRangeArrOfDupWords
End If
End If
Next
'============================================================
'** this part highlights words that are repeated "n" times
'loop through dict. items array
For Each var In WordsDict.Keys
'replace the "2" with "n" if you want to highlight the words that are repeated "n" times
If UBound(WordsDict.Item(var)) = 2 Then
ThisDocument.Range(WordsDict.Item(var)(1), WordsDict.Item(var)(2)).HighlightColorIndex = wdBrightGreen
End If
Next
'============================================================
End Sub
Function GetWordRangeArray(WordObject) As Variant()
'static variant array of two item
Dim RangeValue(1 To 2)
'store the starting range
RangeValue(1) = WordObject.Start
'store the end range, (-1) neglect space at the end of word
RangeValue(2) = WordObject.End - 1
'returned value
GetWordRangeArray = RangeValue
'clear the array
Erase RangeValue
End Function
code
Dim RangeValue(1 To 1) RangeValue(1) = WordObject.Start andcode
ThisDocument.Range(WordsDict.Item(var)(1), WordsDict.Item(var)(1) + Len(var))。 - Ali_R4v3nWordObject.End - 1
:单词后面的句点或逗号会截断最后一个字母。 - omegastripes