1

我编写了这段代码来删除 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
4

1 回答 1

2

问题是你的Condin the function 和Condin the sub 不一样。它们都是局部变量。您可以使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
于 2012-06-26T13:33:58.567 回答