Highlight list words in a MS Word file

白昼怎懂夜的黑 提交于 2020-07-22 21:34:41

问题


First I want to say that I don't know anything about VBA and I want to highlight list words which is in A.txt(or .doc) file to a MS-Word file B.docx that full of texts. I found a VBA code that works perfectly fine but It needs you put words into the code StrFnd = "dog,cat,pig,horse,man". Can you help me change it somehow the code gets list words file A.txt instead of typing these words. Thank you very much.

Sub HiLightList()
Application.ScreenUpdating = False
Dim StrFnd As String, Rng As Range, i As Long
StrFnd = "dog,cat,pig,horse,man"
For i = 0 To UBound(Split(StrFnd, ","))
  Set Rng = ActiveDocument.Range
  With Rng.Find
    .ClearFormatting
    .Text = Split(StrFnd, ",")(i)
    .Replacement.ClearFormatting
    .Replacement.Highlight = True
    .Replacement.Text = "^&"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = True
    .Execute Replace:=wdReplaceAll
  End With
Next
Set Rng = Nothing
Application.ScreenUpdating = True
End Sub

回答1:


Ok, this will look at the first document for the list of words, then highlight the same words in the current document.

Sub CompareWordList()
  Dim sCheckDoc As String
  Dim docRef As Document
  Dim docCurrent As Document
  Dim wrdRef As Object

sCheckDoc = "C:\highlight\A.txt"
Set docCurrent = Selection.Document
Set docRef = Documents.Open(sCheckDoc)
docCurrent.Activate

With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Font.Bold = True
    .Replacement.Text = "^&"
    .Forward = True
    .Format = True
    .MatchWholeWord = True
    .MatchCase = True
    .MatchWildcards = False
End With

For Each wrdRef In docRef.Words
    If Asc(Left(wrdRef, 1)) > 32 Then
        With Selection.Find
            .Wrap = wdFindContinue
            .Text = wrdRef
            .Execute Replace:=wdReplaceAll
        End With
    End If
Next wrdRef

docRef.Close
docCurrent.Activate
End Sub


来源:https://stackoverflow.com/questions/46142800/highlight-list-words-in-a-ms-word-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!