I am currently working on developing a word macro that involves changing specific text color to wdRed with the help of wildcards based on an excel file. I have managed to create a macro that successfully highlight specific text based on an excel file:
Code: Select all
Sub HighlightText()
Dim excelFilePath As String
Dim ExcelApp As Object
Dim ExcelWorkbook As Object
Dim ExcelWorksheet As Object
Dim wordDoc As Document
Dim findRange As range
Dim findText As String
Dim wildcardFlag As String
excelFilePath = "D:\Database.xlsx"
' Create an instance of Excel and open the workbook
Set ExcelApp = CreateObject("Excel.Application")
Set ExcelWorkbook = ExcelApp.Workbooks.Open(excelFilePath)
' Set the worksheet to be used
Set ExcelWorksheet = ExcelWorkbook.Sheets(2)
' Set the Word document to be used
Set wordDoc = ActiveDocument
' Loop through the rows in the Excel file
For i = 2 To ExcelWorksheet.Cells(ExcelWorksheet.rows.Count, 1).End(-4162).Row ' -4162 represents xlUp
' Get the text to find from Column A
findText = ExcelWorksheet.Cells(i, 1).value
' Get the wildcard flag from Column B
wildcardFlag = ExcelWorksheet.Cells(i, 2).value
' Find the text in the Word document
Set findRange = wordDoc.range
With findRange.Find
.ClearFormatting
.text = findText
' Use wildcard if the flag is "T"
If wildcardFlag = "T" Then
.MatchWildcards = True
End If
' Highlight the found text with yellow color
Do While .Execute
findRange.HighlightColorIndex = wdYellow
findRange.Collapse wdCollapseEnd
Loop
End With
Next i
' Close the Excel workbook and quit Excel
ExcelWorkbook.Close
ExcelApp.Quit
' Clean up the objects
Set ExcelWorksheet = Nothing
Set ExcelWorkbook = Nothing
Set ExcelApp = Nothing
Set findRange = Nothing
Set wordDoc = Nothing
End Sub
For example, Highlight "ABC" in a sentence:
ABC, and other individuals, are always ready and willing to help you.
If I use the following wildcards:
Find: ABC[!Members]
the Result:
ABC, and other individuals, are always ready and willing to help you.
In any case, the comma following "ABC" will also be highlighted.
What I expect is to edit this macro so that it change specific text font color to wdRed, but not highlight them in wdYellow, and also resolve the above issue raised.
May I ask if anyone can kindly assist me in achieving this task? Thank you very much in advance.
Here are documents and Excel file for your further action: