我正在尝试创建一个要在 Microsoft Word 2007 中使用的宏,它将在文档中搜索位于外部 Excel 文件中的多个关键字(字符串变量)(将其放在外部文件中的原因是这些术语通常是更改和更新)。我已经弄清楚如何逐段搜索文档以查找单个术语并为该术语的每个实例着色,并且我认为正确的方法是使用动态数组作为搜索术语变量。
问题是:如何让宏创建一个包含外部文件中所有术语的数组并在每个段落中搜索每个术语?
这是我到目前为止所拥有的:
Sub SearchForMultipleTerms()
'
Dim SearchTerm As String 'declare search term
SearchTerm = InputBox("What are you looking for?") 'prompt for term. this should be removed, as the terms should come from an external XLS file rather than user input.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatti…
With Selection.Find
.Text = SearchTerm 'find the term!
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
While Selection.Find.Execute
Selection.GoTo What:=wdGoToBookmark, Name:="\Para" 'select paragraph
Selection.Font.Color = wdColorGray40 'color paragraph
Selection.MoveDown Unit:=wdParagraph, Count:=1 'move to next paragraph
Wend
End Sub
感谢您的关注!
最佳答案
也许在这些方面有一些东西:
Dim cn As Object
Dim rs As Object
Dim strFile, strCon
strFile = "C:\Docs\Words.xls"
'' HDR=Yes, so there are column headings
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
'' The column heading (field name) is Words
strSQL = "SELECT Words FROM [Sheet5$]"
rs.Open strSQL, cn
Do While Not rs.EOF
Selection.Find.ClearFormatting
With Selection.Find
.Text = rs!Words '' find the term!
.Forward = True
.Wrap = wdFindContinue
.MatchWholeWord = True
End With
While Selection.Find.Execute
Selection.GoTo What:=wdGoToBookmark, Name:="\Para" 'select paragraph
Selection.Font.Color = wdColorGray40 'color paragraph
Selection.MoveDown Unit:=wdParagraph, Count:=1 'move to next paragraph
Wend
rs.Movenext
Loop
关于vba - 在 VBA 中搜索多个术语的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464689/