循环中的.FindNext不起作用

时间:2014-10-20 08:25:15

标签: excel vba loops find set

我正在使用此循环来查找值。 .Find工作,但findNext没有,省略许多值。我放弃了我的代码,你有什么建议吗?非常感谢你!

For Each ws In SourceWb.Worksheets
    If IsNumeric(Left(ws.Name, 3)) Then
        Set gCell = ws.Columns(6).Find(what:=numdoc, LookIn:=xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, searchformat:=False)
        If Not gCell Is Nothing And IsNumeric(Left(gCell.Parent.Name, 3)) Then

            firstAddress = gCell.Address

            Do
                repetidos = repetidos + 1
                finalcell = gCell.Address
                'merged cells code here not displayed
                oldaddress = gCell.Address
                '>Having trouble here> **
                Set gCell = ws.Columns(6).FindNext(after:=gCell)
                '**


            Loop Until gCell.Address = oldaddress
        End If
    End If
Next ws

2 个答案:

答案 0 :(得分:0)

这是我从你的线索中得到的最好的结果:

Option Explicit

Sub Test()
Dim WS As Worksheet
Dim SourceWB As Workbook
Dim numdoc As Long
Dim gCell As Range
Dim firstAddress As String
Dim oldaddress As String
Dim finalcell As String
Dim repetidos As Long

Set SourceWB = ThisWorkbook 'added for clarity and safety
numdoc = 456
    For Each WS In SourceWB.Worksheets
        If IsNumeric(Left(WS.Name, 3)) Then 'OK I had to save it as "123 A"
            Set gCell = WS.Columns(6).Find(what:=numdoc, _
                LookIn:=xlValues, _
                lookat:=xlWhole, _
                SearchOrder:=xlByRows, _
                MatchCase:=False, _
                searchformat:=False)
            If Not gCell Is Nothing And IsNumeric(Left(gCell.Parent.Name, 3)) Then
                firstAddress = gCell.Address
                Set gCell = WS.Columns(6).FindNext(after:=gCell)
                Do
                    repetidos = repetidos + 1
                    finalcell = gCell.Address
                    'merged cells code here not displayed
                    oldaddress = gCell.Address
                Loop Until gCell.Address = oldaddress
            End If
        End If
    Next WS
End Sub

不确定它是否回答了问题,但它确实显示了缩进。

那里有With...End With的空间,但我太累了,无法找到它。

答案 1 :(得分:0)

 This seems to work at this point.

 For Each WS In SourceWB.Worksheets
    With ws.Range("F:F")
    If IsNumeric(Left(WS.Name, 3)) Then 'OK I had to save it as "123 A"
        Set gCell = .Find(what:=numdoc, _
            LookIn:=xlValues, _
            lookat:=xlWhole, _
            SearchOrder:=xlByRows, _
            MatchCase:=False, _
            searchformat:=False)
        If Not gCell Is Nothing And IsNumeric(Left(gCell.Parent.Name, 3)) Then
            firstAddress = gCell.Address
            Set gCell = .FindNext(after:=gCell)
            Do


                'merged cells code here not displayed

            Loop While Not gCell Is Nothing And gCell.Address <> firstAddress
        End If
    End If
 end with
Next WS