2012-06-26 180 views
0

我已經編寫了此代碼以刪除Excel電子表格的列中的重複行。我不知道如何或者如果可能的話,從函數內部退出while循環。我不想在循環中添加第二個條件(如Counter < 100),因爲我不希望它運行超過需要。從遞歸函數退出while循環

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 

回答

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 
+0

This works。謝謝! – dronae