一段代码只按预期运行多次

目前我正在debugging一段代码。 目前我的代码按预期工作,它将date分配给finaldatevariables,然后在代码中查找以删除高于finaldatevariables的所有date。 唯一的问题是子程序需要多次运行才能生效。 例如,当我运行一次,它删除了大约一半的date,再次运行它,它也是这样,我通常F5大约5次,以确认它的完整。 虽然这是很好的debugging,我需要知道这将会完美的每一次。

Sub Remove_Unecessary_Data_1() Dim ALLCs As Worksheet Dim DS As Worksheet Dim finaldate As Date Set DS = Sheets("Data Summary") Set ALLCs = Sheets("Asset LLC (Input)") ALLCs.Select For y = 1 To 40 If InStr(1, Cells(13, y), "Timestamp of Execution") Then finaldate = ALLCs.Cells(50, y) End If Next ALLCs.Select For u = 1 To 40 If InStr(1, Cells(13, u), "Start Date") Then For p = 2 To 69584 If Cells(p + 14, u) > finaldate Then Cells(p + 14, u).EntireRow.Delete End If Next End If Next end sub 

编辑:示例数据

细胞(50,y)= 1/12/15 finaldate =细胞(50,Y)

开始date栏包含从1/05/15到1/30/15范围内的date。

在2015年1月12日以后的所有date,如果工作正常,应该将整行消除。

删除行时,必须从下到上工作,否则会跳过行。

例如,你有:

  Line 1 >Line 2 Line 3 Line 4 

当你的代码删除, Line 2行,现在“Row”3变成了“Row”2,但是你的代码移到了Line 4 。 你的数据现在看起来像这样:

  Line 1 Line 3 >Line 4 

如果你改变你的代码的这一点:

 For p = 2 To 69584 If Cells(p + 14, u) > finaldate Then Cells(p + 14, u).EntireRow.Delete End If Next 

对此:

 For p = 69598 to 16 step - 1 If Cells(p, u) > finaldate Then Cells(p, u).EntireRow.Delete End If Next 

一切都应该没问题。

*注意:我将开始和结束点数调整了14,并从Cells()参考中删除了Cells() 。 没有意义在那里做额外的math…

当使用以下命令删除一行时:

 Cells(p + 14, u).EntireRow.Delete 

被删除的行下方的行向上移动以占据该空间。 如果该行包含应该删除的date,则会被忽略,因为计数器会自动移到下一行。 例如,假设我们希望删除“ Data列中的任何具有CD的行:

 Row Number Data 1 A 2 B 3 C 4 D 5 E 

变为:

 Row Number Data 1 A 2 B 3 D 4 E 

行计数器移动到4而不检查3中的新值,所以D不会被删除。

您可以通过将您的If...Then语句更改为Do...While循环来解决此问题:

 Sub Remove_Unecessary_Data_1() Dim ALLCs As Worksheet Dim DS As Worksheet Dim finaldate As Date Set DS = Sheets("Data Summary") Set ALLCs = Sheets("Asset LLC (Input)") ALLCs.Select For y = 1 To 40 If InStr(1, Cells(13, y), "Timestamp of Execution") Then finaldate = ALLCs.Cells(50, y) End If Next ALLCs.Select For u = 1 To 40 If InStr(1, Cells(13, u), "Start Date") Then For p = 2 To 69584 Do While (Cells(p + 14, u) > finaldate) Cells(p + 14, u).EntireRow.Delete Loop Next End If Next End sub 

这应该继续检查该单元格删除了前一行,以确保replace行也不应删除。

在行数越来越多的时候删除一行,你会错过分析刚刚删除的行之后的每一行,因为它(行(i + 1))已经成为行(i),而你增加了下一个。

这是你的代码考虑到这一点(并摆脱了无用的Select

 Sub Remove_Unecessary_Data_1() Dim ALLCs As Worksheet, _ DS As Worksheet, _ FinalDate As Date Set DS = Sheets("Data Summary") Set ALLCs = Sheets("Asset LLC (Input)") For y = 1 To 40 If InStr(1, ALLCs.Cells(13, y), "Timestamp of Execution") Then FinalDate = ALLCs.Cells(50, y) End If Next For u = 1 To 40 If InStr(1, ALLCs.Cells(13, u), "Start Date") Then For p = 69584 To 2 Step -1 If Cells(p + 14, u) > FinalDate Then Cells(p + 14, u).EntireRow.Delete End If Next End If Next End Sub