vba - 在 VBA 中搜索多个术语的文档?

标签 vba search ms-word excel

我正在尝试创建一个要在 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/

相关文章:

excel - 使用 ws.QueryTables.Add 导入 CSV 时出现问题

PHP - 从上传的 Microsoft Word 文档中获取字数

regex - 在 MS Word 正则表达式中捕获组

vba - 在 Access 中隐藏和重新显示自定义弹出总机?

vba - Excel VBA : How to solve Run-time error '91' ?

VBA - 错误 1004 - 方法类的 CopyPicture 失败

python - os.system ('grep "word"file.txt') 的 pythonic 方式是什么?

ruby-on-rails - 在 Ruby on Rails 中搜索的最佳选择是什么?

javascript - 通过大型 js 字符串数组优化搜索?

html - 如何在 ASP.NET 中生成 Word 文档(doc,docx)?