Home » excel » arrays – Excel VBA – Search for string in worksheet

arrays – Excel VBA – Search for string in worksheet

Posted by: admin April 23, 2020 Leave a comment


I’ve got this Excel Workbook which I want to search for a specific string in Sheet1. If it finds it, enter a new value. But, the sheet is pretty huge, so I don’t think it would be very efficient to loop through each cell. So, can I search through a range and find it that way?

This is what I’ve got so far:

Dim rngSearchRange as range

    With ThisWorkbook.Sheets(1)
      Set rngSearchRange = .Range("A2:A" & .Range("A" & Rows.Count).End(xlUp).Row)
    End With

The string I’m looking for is the first value in an array of three values. So, how can I search this range for that specific string, find the position and then enter a new value?

I was thinking something along this:

Dim rngFindRange as range
Set rngFindRange = rngSearchRange.Find(var(0), LookIn:=xlValues, lookat:=xlWhole)

The var(0) is the value in the array I’m after. But this line doesn’t really give me any results. Am I way off here?

How to&Answers:

something like this

Sub FindMe()
    Dim ws As Worksheet
    Dim rngSearchRange As Range
    Dim rngFindRange As Range
    Dim Var
    Dim elemVar
    Var = Array("apples", "oranges", "fruit")
    Set ws = ThisWorkbook.Sheets(1)
    Set rngSearchRange = ws.Range(ws.[a2], ws.Cells(Rows.Count, "A").End(xlUp))
    For Each elemVar In Var
        Set rngFindRange = rngSearchRange.Find(elemVar, LookIn:=xlValues, lookat:=xlWhole)
        If Not rngFindRange Is Nothing Then
            MsgBox elemVar & " found in " & rngFindRange.Address(0, 0)
            MsgBox elemVar & " not found in:"
        End If
    Next elemVar
End Sub