如何编写VB脚本以在所有单元格中查找多个关键字并突出显示每个关键字?

时间:2016-11-18 05:32:36

标签: excel vba excel-vba keyword-search

我目前有一个关键字列表(例如CFO,CTO,临时经理等),我希望将一个宏分配给一个按钮,该按钮可以搜索包含在表1的E列中的所有单元格然后,这些关键字会返回结果,并在单元格中突出显示关键字。

  • 每个关键字都位于工作表2的A列中的单独单元格中。
  • 如果列表中有一个关键字,它将搜索一个,但如果有更多,则搜索组合。

以下是用于说明我上面描述的内容的截图

enter image description here

我在互联网上发现了一些建议使用AutoFilter但我只能用它来搜索一个关键字。这就是我尝试过的:

\"

提前致谢。

1 个答案:

答案 0 :(得分:0)

以下代码将使用相同颜色为所有匹配着色(我选择了蓝色)。您可以在模块中编写此宏,然后创建一个表单控件按钮并将宏指定给该按钮。

Sub macro()
Dim a As Integer, x As String, mystring As String
a = 2
Sheets("Sheet2").Activate
Cells(a, 1).Activate
Do While ActiveCell.Value <> ""
    x = ActiveCell.Value
    p = Len(x)
    Application.GoTo Sheet1.Range("E2")
    Do While ActiveCell.Value <> ""
        mystring = ActiveCell.Value
        If InStr(mystring, x) > 0 Then
            Position = InStr(1, mystring, x)
            If Position > 0 Then
                ActiveCell.Characters(Position, p).Font.Color = RGB(255, 0, 0)
            End If
        End If
        ActiveCell.Offset(1, 0).Activate
    Loop
    a = a + 1
    Application.GoTo Sheet2.Cells(a, 1)
Loop
End Sub

如果您有任何其他特定要求,请告知我们,以便可以更改代码。我希望这会有所帮助。