View Single Post
 
Old 01-18-2023, 10:45 PM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2019
Expert
 
Join Date: Aug 2014
Posts: 4,101
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

There's a third way - and that's to read the text file directly to an array without opening it e.g. Using Andrew's code as an example.

Code:
Sub ReplacefromTXT()
'Graham Mayor - https://www.gmayor.com - Last updated - 19 Jan 2023
Dim FSO As Object, oFile As Object
Dim arrFind() As String, sFind As String
Dim oDoc As Document
Dim i As Integer
Const sName As String = "C:\Test\Test.txt" ' change this to your text file full name

       
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set oFile = FSO.OpenTextFile(sName, 1)
    arrFind = Split(oFile.ReadAll, vbNewLine)

    Set oDoc = ActiveDocument
    Options.DefaultHighlightColorIndex = wdRed
    With oDoc.Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Font.Bold = True
        .Replacement.Highlight = True
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchWholeWord = False
        .MatchCase = True
        .MatchWildcards = False
        For i = LBound(arrFind) To UBound(arrFind)
            sFind = Trim(arrFind(i))
            If Len(sFind) > 1 Then
                .Text = sFind
                .Execute Replace:=wdReplaceAll
            End If
        Next i
    End With
lbl_Exit:
    Set FSO = Nothing
    Set oFile = Nothing
    Set oDoc = Nothing
    Exit Sub
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote