如何查找并突出显示 ActiveSheet 中所有出现的多个字符串?

How to find and highlight all occurrences of multiple strings within the ActiveSheet?

我已经找到了解决方案,但代码太长了。然后我决定寻找一种方法,将我想要查找并突出显示的所有单词插入到一个查找方法中。我遇到了一些使用数组的想法,并使用这 3 个代码来编写我的代码 (this, this, and this),但我是 VBA 的新用户,所以我的最终代码有问题,它只突出显示数组的最后一个字符串。我认为问题是逻辑问题,但我不了解 VBA 的基础知识,所以我不知道如何更正它。

我的实际代码:

Sub Sample()
Dim fnd As String
Dim MyAr
Dim i As Long
Dim rng As Range, FoundCell As Range, LastCell As Range, myRange As Range

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

fnd = "hugo/vw/osnabrück"

MyAr = Split(fnd, "/")

    For i = LBound(MyAr) To UBound(MyAr)

        Set FoundCell = myRange.Find(what:=MyAr(i), after:=LastCell)

        If Not FoundCell Is Nothing Then
            FirstFound = FoundCell.Address
        End If
Set rng = FoundCell
            Do Until FoundCell Is Nothing
                Set FoundCell = myRange.FindNext(after:=FoundCell)
                    Set rng = Union(rng, FoundCell)
                If FoundCell.Address = FirstFound Then Exit Do
            Loop
    Next i

If Not rng Is Nothing Then
    rng.EntireRow.Interior.ColorIndex = 3
End If
End Sub

例如,使用这段代码我可以找到并突出显示所有 "Osnabrück" 但它不会突出显示任何 Hugo 或 VW。

这是因为你只在代码的最后做了一次高亮显示,而你数组中的最后一个选择恰好是 osnabruck。

你需要搬家

If Not rng Is Nothing Then
    rng.EntireRow.Interior.ColorIndex = 3
End If

就在

之前
next i

这样它就会对数组中的每个元素执行 if。