How do I find and highlight all occurrences of multiple lines in an ActiveSheet?

I found the solution already, but the code is too long. Then I decided to find a way to insert all the words I want to find and highlight in one search method. I came across some ideas of using arrays to do this and used these 3 codes to write mine ( this , this and this ), but I'm a new VBA user, so my last code has a problem, it underlines just the last line of the array. I think the problem is in logic, but I don't know the basics of VBA, so I have no idea how to fix it.

My actual code:

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

      

For example, with this code, I can find and highlight all "Osnabrück", but not highlight Hugo or VW.

+3


source to share


1 answer


This is because you only make the selection once at the very end of the code, and the last selection in your array is usually osnabruck.

You need to move

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

      



before

next i

      

so that it gets executed if for each element of the array.

+3


source







All Articles