Excel VBA - 在工作表中搜索字符串

时间:2011-10-03 10:17:07

标签: arrays excel excel-vba vba

我有这个Excel工作簿,我想在Sheet1中搜索特定的字符串。如果找到,请输入新值。但是,工作表非常庞大,所以我认为循环每个单元格并不是非常有效。那么,我可以搜索一个范围并找到它吗?

这是我到目前为止所得到的:

Dim rngSearchRange as range

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

我正在寻找的字符串是三个值数组中的第一个值。那么,如何在该范围内搜索该特定字符串,找到位置然后输入新值?

我在想这件事:

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

var(0)是我之后的数组中的值。但这条线并没有给我任何结果。我离开这里了吗?

1 个答案:

答案 0 :(得分:3)

类似这样的事情

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