Sub test()
Dim mainTextCell As Range, MainText As String
Dim keyWordRange As Range
Dim oneCell As Range, oneKeyword As String
Dim colOffset As Long
Set mainTextCell = Sheet1.Range("A1")
Set keyWordRange = Sheet1.Range("B3:B6")
MainText = Application.Trim(CStr(mainTextCell.Value))
MainText = Replace(MainText, ",", vbNullString)
MainText = Replace(MainText, ";", vbNullString)
MainText = Replace(MainText, ":", vbNullString)
MainText = Replace(MainText, ".", vbNullString)
MainText = Replace(MainText, "!", vbNullString)
MainText = Replace(MainText, "?", vbNullString)
MainText = Replace(MainText, "'", vbNullString)
MainText = Replace(MainText, """", vbNullString)
MainText = Replace(MainText, ",", vbNullString)
MainText = Replace(MainText, ",", vbNullString)
For Each oneCell In keyWordRange.Cells
With oneCell
colOffset = 0
oneKeyword = CStr(.Value)
Do
colOffset = colOffset + 1
With .Offset(0, colOffset)
Rem font to normal
With .Font
.Bold = False
.Underline = False
.ColorIndex = xlAutomatic
End With
.Value = WordsSurrounding(MainText, oneKeyword, 5, colOffset)
Rem highlight keyword
With .Characters(InStr(1, .Value, " " & oneKeyword & " ") + 1, Len(oneKeyword))
With .Font
.Bold = True
.Underline = True
.ColorIndex = 3
End With
End With
End With
Loop Until .Offset(0, colOffset).Value = vbNullString
End With
Next oneCell
End Sub
Function WordsSurrounding(ByVal bigText As String, ByVal keyWord As String, ByVal countOfWords As Long, _
Optional Occurance As Long = 1) As String
Dim splitSentence As Variant
Dim preceedingWords As String, pWords As Variant
Dim followingWords As String, fWords As Variant
Dim i As Long
bigText = Application.Trim(bigText)
splitSentence = Split(" " & bigText & " ", " " & keyWord & " ")
If Occurance < UBound(splitSentence) + 1 Then
preceedingWords = Trim(splitSentence(Occurance - 1))
End If
If Occurance <= UBound(splitSentence) Then
followingWords = Trim(splitSentence(Occurance))
End If
pWords = Split(preceedingWords, " ")
fWords = Split(followingWords, " ")
For i = 0 To UBound(pWords) - countOfWords
pWords(i) = vbNullString
Next i
preceedingWords = Trim(Join(pWords, " "))
For i = countOfWords To UBound(fWords)
fWords(i) = vbNullString
Next i
followingWords = Trim(Join(fWords, " "))
If Len(followingWords) + Len(preceedingWords) > 0 Then
WordsSurrounding = Application.Trim(preceedingWords & " " & keyWord & " " & followingWords)
End If
End Function