查找范围内的值

时间:2017-04-12 23:42:02

标签: vba excel-vba excel

我正在编写一个子程序,查看从包含String值的单元格A1(范围是1列宽)开始的一系列单元格。我的sub首先找到整个范围并将其分配给Range变量“theForest”以帮助简化搜索。然后,它查看范围中的每个单元格,直到找到单词“Edward”。如果找到了他,他会在一条消息中显示结果(说明他曾经或未被发现)。

到目前为止我的代码是:

With Range("A1")
     'this will help find the entire range, since it is only one column I will search by going down
   theForest = Range(.Offset(0,0), .End(xlDown)).Select
   Dim cell As Range
   For Each cell In theForest
        If InStr(Edward) Then
            Msgbox"He was found"
        Else
            Msgbox"He was not found sorry"
        End If
   Next cell
End With

但是我在运行程序时遇到了很多错误,我认为问题出在

theForest = Range(.Offset(0,0), .End(xlDown.)).Select 

代码行。我很感激对这个简单代码的任何指导。

谢谢:)

编辑:这是我提出的一些新代码:

Dim isFound As Boolean
isFound = False
With Range("A1")
    For i = 1 to 500
        If .Offset(1,0).Value = "Edward" Then
            isFound = True
            Exit For
        End If
    Next
End With
If isFound = True Then
    Msgbox " Edward was found"
Else
    MsgBox "Edward was not found"
End if

然后它再次不包括查找整个范围并将其分配给范围变量theForest。

1 个答案:

答案 0 :(得分:0)

 Dim theForest as Range, f as Range


 Set theForest = ActiveSheet.Range(ActiveSheet.Range("A1"), _
                                     ActiveSheet.Range("A1").End(xlDown))

 Set f = theForest.Find("Edward", lookat:=xlWhole) 

 If Not f Is Nothing Then
      Msgbox"He was found"
 Else
     Msgbox"He was not found sorry"
 End If