PROBLEM
I’m trying to make a macro which allows me to enter in a reference numeral (e.g., 102) and have the entire document be scanned for instances of that reference numeral. I want the code to identify 2-word strings which immediately precede each instance of that reference numeral, and I want the most commonly appearing 2-word string (i.e., the mode of all the 2-word strings preceding the reference numeral) to be returned/output. This way, if “black sheep 106” is repeatedly referenced in the document, entering “106” will return “black sheep”. Choosing the modal 2-word string just accounts for any discrepancies or inconsistencies in naming used throughout the document, e.g., sometimes “sheep 106, which is black” might be used in the doc, or the wrong reference numeral used in error, etc.
My code does not work, though:
Sub FindFeature()
Dim refNum As String
Dim doc As Document
Dim rng As Range
Dim wordArray() As String
Dim wordDict As Object
Dim maxCount As Long
Dim commonString As String
Dim i As Long
' Set the reference numeral (e.g., "102")
refNum = InputBox("Enter the reference numeral:")
' Initialize dictionary to store word frequencies
Set wordDict = CreateObject("Scripting.Dictionary")
' Set the document to the active document
Set doc = ActiveDocument
' Loop through all words in the document
For Each rng In doc.Words
' Check if the word is the reference numeral
If IsNumeric(rng.text) And rng.text = refNum Then
' Get the 2-word string preceding the reference numeral
wordArray = Split(rng.Previous.text, " ")
If UBound(wordArray) >= 1 Then
' Construct the 2-word string (last two words)
Dim key As String
For i = UBound(wordArray) - 1 To UBound(wordArray)
key = key & wordArray(i) & " "
Next i
key = Trim(key)
' Add the 2-word string to the dictionary
If Not wordDict.Exists(key) Then
wordDict.Add key, 1
Else
wordDict(key) = wordDict(key) + 1
End If
' Update the maximum count and common string
If wordDict(key) > maxCount Then
maxCount = wordDict(key)
commonString = key
End If
End If
End If
Next rng
' Display the most common 2-word string
If commonString <> "" Then
MsgBox "Reference numeral " & refNum & ": " & commonString
Else
MsgBox "No feature with reference numeral " & refNum & " found."
End If
End Sub
Any ideas how to fix it?
cjrc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.