从递归函数退出while循环

时间:2012-06-26 13:24:09

标签: vba excel-vba excel

我已编写此代码以删除Excel电子表格列中的重复行。我不确定如何,或者是否有可能从函数本身退出while循环。我不想在循环中添加第二个条件(例如Counter < 100),因为我不希望它运行超过需要。

Sub Deletion()
Dim Cond As Boolean
Dim Counter As Integer
Cond = True
Counter = 2
    While Cond = True
    RecDel (Counter)
    Counter = Counter + 1
    Wend
End Sub

Function RecDel(Varii As Integer)
Set CurrentCell = Workbooks("Duplicate.xls").Sheets("Sheet1").Cells(Varii, 2)
        If CurrentCell.Value = CurrentCell.Offset(1, 0).Value And CurrentCell.Offset(1, 0).Value <> "" Then
                Workbooks("Duplicate.xls").Sheets("Sheet1").Rows(Varii + 1).Delete
                RecDel (Varii) 'Repeats deletion until this row and the next row are different
        ElseIf CurrentCell.Offset(1, 0).Value = "" Then
            Cond = False  'This can't change the global variable and break the loop
        Else
        End If
End Function

1 个答案:

答案 0 :(得分:2)

问题是函数中的Cond和子函数中的Cond不一样。它们都是局部变量。你可以让Cond全局在2之间共享它。或者,你可以让你的函数返回一个布尔值并完全删除Cond标志:

Function RecDel(Varii As Integer) As Boolean
    Set CurrentCell = Workbooks("Duplicate.xls").Sheets("Sheet1").Cells(Varii, 2)
    If CurrentCell.Value = CurrentCell.Offset(1, 0).Value And CurrentCell.Offset(1, 0).Value <> "" Then
        Workbooks("Duplicate.xls").Sheets("Sheet1").Rows(Varii + 1).Delete
        RecDel = RecDel (Varii) 'Repeats deletion until this row and the next row are different
    ElseIf CurrentCell.Offset(1, 0).Value = "" Then
        RecDel = False  'This can't change the global variable and break the loop
    End If
End Function

在你的主叫子中,检查RecDel的状态:

While RecDel (Counter) = True
    Counter = Counter + 1
Wend