我有一个文件,里面有要搜索的单词。我想在活动文档中突出显示这些单词。
例如:style.docx:
school
Agro commercial
abovementioned
some words
physics
活动文档:
这是解释一些词语(例如上述和学校)的行。
这是行的结尾。
预期输出:一些单词、上述、学校应该在活动文档中突出显示。
我已经尝试过下面提到的代码:
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
我已粘贴我的答案,其中以黄色突出显示多个搜索词(来自其他文件)。可以使用文件对话框对象选择搜索词文件和要突出显示的文件。
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