Find方法使用VBA继续丢失excel工作簿中的搜索字符串?

时间:2011-10-04 15:36:01

标签: excel vba find excel-2007

我在客户提供的Excel工作表中搜索文本/字符串。问题是有时excel Find功能有效,有时则不行。例如,如果excel表格如下所示:

PartID Description Reference  
1234    abc         R3
4567    def         C34
4512    ghi         R2

让我说我搜索了R2并找到了它,但是当我搜索R3时它就不会命中它。它会在R2之后找到任何类似R3的东西,如R33,R31等。看起来它从它的最后位置开始检查,这是R2的位置。以下是我的功能:

Sub addFeedernoToFile(PARTS As Integer, ByRef counter As Integer, fileptrsq As String, ws_sq As Worksheet, tempList() As String)

    Dim i As Integer, k As Integer, found As Integer
    Dim LastAddress As String

    Dim xlSearchWithin1 As XlSearchWithin

    Set Search_Range = Columns("C")

        For i = 1 To PARTS
            searchstring = tempList(counter)

            With Search_Range
                Set c = ws_sq.Cells.Find(What:=searchstring, _
                                         After:=ws_sq.Range("C3"), _
                                         SearchOrder:=xlByColumns, _
                                         MatchCase:=False, _
                                         LookAt:=xlPart, _
                                         SearchDirection:=xlNext)

                On Error Resume Next
              ' keep track of where we are. If we are in the loop below and hit            
              ' LastAddress this means we have looped back to the begining.
                LastAddress = c.Address     

                'loop until we find the part
                Do Until c Is Nothing

                    found = 1
                    Dim splitter() As String

                    splitter = Split(c.Value, ",")

                    For k = 0 To UBound(splitter)
                        If splitter(k) = searchstring Then
                            firstaddress = c.Address
                            itemRow = Mid(firstaddress, 4, Len(firstaddress) - 3)
                            feederno = ws_sq.Range("F" & itemRow)
                            counter = counter - 1
                            found = 0
                            Exit For
                        End If
                    Next

                    Set c = ws_sq.Cells.FindNext(After:=c)

                   'we loop until we find our part the file, and if found
                    'we break out then.
                    If found = 0 Then
                        Exit Do
                    End If

                    If LastAddress = c.Address Then
                        Exit Do
                    End If
                Loop    ' end do until
            End With    ' end with search_range
        Next            ' end for
End Sub

谢谢。

1 个答案:

答案 0 :(得分:0)

看起来它并没有立刻抓住R3,因为你从C3开始,最终它应该在你搜索其他所有内容之后点击它。请记住参数“After:=”表示在该单元格之后它将开始搜索,因此您可能希望在C2处开始搜索,因此您需要放置

After:=ws_sq.Range("C1")

此外,如果您想进行精确搜索,可以使用

LookAt:=xlWhole

使用xlPart,您将获得其他所有内容。这段代码将使您从最后一个位置开始:

Set c = ws_sq.Cells.FindNext(After:=c)

但你做的主要搜索不会这样做。