如何突出显示文档中的多个搜索词?

时间:2014-12-09 05:44:13

标签: vba ms-word word-vba

我有一个文件,其中包含要搜索的单词。我想在活动文档中突出显示这些词。

例如: style.docx: 农业商业 上述 一些单词 物理 校

活动文档:

这是解释上述和学校等一些词的界限。这是该行的结束。

预期产量: 上述一些词语应在活动文件中突出显示。

我尝试了下面提到的代码:

    Dim docTitle As Document
    Dim docStyle As Document
    Set docTitle = Documents.Open(FileName:="C:\Documents and Settings\quads\Desktop\stylesheet.docx", ConfirmConversions:=True)
    Set docStyle = Documents.Open(FileName:="C:\Documents and Settings\quads\Desktop\files\Albala D-ed.doc", ConfirmConversions:=True)

    Dim char As Long
    Dim x As Long
    Dim count As Integer

    Dim Para As Paragraph

    For Each Para In docTitle.Paragraphs
      If Len(Para.Range.Text) > 0 Then
                ActiveDocument.Range(0, 0).Select

        Selection.Find.ClearFormatting
                With Selection.Find
                .Text = Left(Para.Range.Text, Len(Para.Range.Text) - 1)
                .Replacement.Text = ""
                .Forward = True
                .Wrap = wdFindContinue
                .Format = True
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
            End With
            Selection.Find.Execute

        End If
        ActiveDocument.Range(0, 0).Select

    Next Para

另外,我想搜索特定文件夹中的所有文件(“文件”)而不提及文件名。

1 个答案:

答案 0 :(得分:0)

我已经粘贴了我的答案,该答案以colour黄色突出显示多个搜索过的单词(来自其他文件)。可以使用文件对话框对象选择要搜索的单词文件和文件。

Dim filepath As String
Dim filename As FileDialog
Dim stylepath As String
Dim stylename As FileDialog
MsgBox ("Please choose Style File Name")

Set stylename = Application.FileDialog(filedialogtype:=msoFileDialogFilePicker)
If stylename.Show Then
stylepath = stylename.SelectedItems(1)
End If

Set filename = Application.FileDialog(filedialogtype:=msoFileDialogFilePicker)
If filename.Show Then
filepath = filename.SelectedItems(1)
End If

Dim range As range
Dim i As Long
Dim arr() As String
Dim docTitle As Document
Dim docStyle As Document
    Set docTitle = Documents.Open(stylepath)
    Set docStyle = Documents.Open(filepath)


arr = Split(docTitle.Content.Text, Chr(13))

For i = 0 To UBound(arr)
Set range = docStyle.range

With range.Find
.Text = arr(i)
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute(Forward:=True) = True
range.HighlightColorIndex = wdYellow

Loop

End With
Next
相关问题