突出显示MS Word文件中的列表单词

时间:2017-09-10 16:14:57

标签: vba excel-vba ms-word word-vba excel

首先,我想说我对VBA一无所知,我想突出显示列表词,这是在A.txt(或.doc)文件中到MS- Word文件B.docx 那些文本。我找到了一个完全正常的VBA代码,但它需要你把代码放入代码 StrFnd =“dog,cat,pig,horse,man” 。你能帮我改变一下代码获取列表单词文件A.txt而不是输入这些单词。非常感谢你。

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 个答案:

答案 0 :(得分:0)

好的,这将查看单词列表的第一个文档,然后突出显示当前文档中的相同单词。

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