开发者

Excel VBA - Search for string in worksheet

开发者 https://www.devze.com 2023-04-10 10:56 出处:网络
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开发者_如何转开

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?


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)
        Else
            MsgBox elemVar & " not found in:"
        End If
    Next elemVar
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号