FindNext返回不正确的值

时间:2015-08-07 14:47:35

标签: excel vba find range

我目前遇到以下代码的问题。我设置了Find值,但FindNext不断返回错误的行:

Set SearchRange = Range("B:B")
Set OpenBal = SearchRange.Find("Opening Balance")
Set EndBal = SearchRange.Find("Ending Balance")

Set CritR = Range("E" & OpenBal.Row, "E" & EndBal.Row)
Set SumR = Range("C" & OpenBal.Row, "C" & EndBal.Row)
Obrow = OpenBal.Row - 1

造成麻烦的代码:

For i = 4 To lr
If Cells(i, 2).Value = "Ending Balance" Then

    If Cells(Obrow, 1).Value = "USD" Then

        abc = Application.WorksheetFunction.SumIf(CritR, "OPEN", SumR)
        def = Application.WorksheetFunction.SumIf(CritR, "CXCL", SumR)
        Cells(i + 1, 5).Value = abc + def
        Cells(i + 1, 5).NumberFormat = "#,##0.00;(#,##0.00)"
        Cells(i + 1, 4).Value = "OPEN/CXCL"
        Cells(i + 1, 4).HorizontalAlignment = xlRight
        Cells(i + 1, 4).Font.Bold = True
        Cells(i + 1, 4).Interior.Color = 65535
        Cells(i + 1, 5).Interior.Color = 65535
        Cells(i + 1, 2).Value = "Final Balance"
        Cells(i + 1, 2).Interior.Color = 65535
        Cells(i + 1, 2).Font.Bold = True
        Cells(i + 1, 3).Value = Cells(i, 3).Value - Cells(i + 1, 5).Value
        Cells(i + 1, 3).NumberFormat = "#,##0.00;(#,##0.00)"
        Cells(i + 1, 3).Font.Bold = True
        Cells(i + 1, 3).Interior.Color = 65535

    End If

        Set OpenBal = SearchRange.FindNext(after:=OpenBal)
        Set EndBal = SearchRange.FindNext(after:=EndBal)
        Set CritR = Range("E" & OpenBal.Row, "E" & EndBal.Row)
        Set SumR = Range("C" & OpenBal.Row, "C" & EndBal.Row)
        Obrow = OpenBal.Row - 1
        Debug.Print "Open Balance: "; OpenBal.Row; " Ending Balance: " & EndBal.Row; " OB ROW: "; Obrow
End If

Next

在调试屏幕中,在第一个值之后为Opening Balance行设置的范围是错误的,它只按下面打印结束余额(在第9行之后所有相应的行实际上是结束余额行):

Open Balance:  9  Ending Balance: 17 OB ROW:  8 
Open Balance:  17  Ending Balance: 26 OB ROW:  16 
Open Balance:  26  Ending Balance: 33 OB ROW:  25 
Open Balance:  33  Ending Balance: 9 OB ROW:  32 

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

FindNext()使用之前Find()的条件,无论其操作范围如何。但您可以再次致电Find()并指定After:=参数。

变化:

Set OpenBal = SearchRange.FindNext(after:=OpenBal)
Set EndBal  = SearchRange.FindNext(after:=EndBal)

要:

Set OpenBal = SearchRange.Find(what:="Opening Balance", after:=OpenBal)
Set EndBal  = SearchRange.Find(what:="Ending Balance",  after:=EndBal)