For循环删除行

我正在使用一个macros,列出我select的任何目录中的所有文件名。 我正在编写代码,将文件名拆分成我稍后可以使用的块。 文件名列表从单元格F6开始并在列上运行。 这是我迄今写的代码:

Dim ContractNum As String Dim InvNum As String Dim FileRng As Range Dim FileLastRow As Long Dim File As Range FileLastRow = Sheet1.Range("F" & Rows.Count).End(xlUp).Row Set FileRng = Sheet1.Range("F6:F" & FileLastRow).SpecialCells(xlCellTypeConstants, 23) For Each File In FileRng If File = "Invoice.zip" Or File = "Thumbs.db" Then File.EntireRow.Delete End If Next File For Each File In FileRng ContractNum = Left(File, 4) InvNum = Mid(File, 8, 6) File.Offset(0, -5) = ContractNum File.Offset(0, -4) = InvNum Next File 

到目前为止,我已经得到了这部分工作正常。 我遇到的问题是在所有的目录中使用这个macros,有不需要的文件,如“Thumbs.db”或“Invoice.zip”。 我有一个问题的代码如下:

 For Each File In FileRng If File = "Invoice.zip" Or File = "Thumbs.db" Then File.EntireRow.Delete End If Next File 

我想要这样做是扫描整个文件名列表,如果遇到“Thumbs.db”或“Invoice.zip”的文件名,删除整个行。 到目前为止,这工作…有点。 例如,如果我的列表中有两个名为“Thumbs.db”和“Invoice.zip”的文件,则必须运行macros两次才能删除这两个文件。 很显然,我想一举把它们全部抹去。

根据我的意见,将for循环更改为:

 For i = filelastrow to 6 step -1 If Sheet1.Cells(i,6) = "Invoice.zip" Or Sheet1.Cells(i,6) = "Thumbs.db" Then Sheet1.row(i).Delete End If Next File 

问题是当一行被删除时,下面的一行变成了那一行,然后循环跳到下一行。 它也将在最后通过空行。

通过倒退,这​​个问题被消除了。

好问题! @Scott Craner的答案很好地诀窍(upvoted顺便说一句),结束了一个可读,有效的VBA切片。 好东西!

还有另一种快速删除行的方法,我认为值得一提: Range.Autofilter策略! 检查一下,Autofilter策略从下面的评论开始:

 Public Sub DeleteRowsWithAutofilter() Dim ContractNum As String Dim InvNum As String Dim FileRng As Range Dim FileLastRow As Long Dim File As Range Dim t As Single t = Timer FileLastRow = Sheet2.Range("F" & Rows.Count).End(xlUp).Row 'Identify the total range of filenames, including the header Set FileRng = Sheet2.Range("F5:F" & FileLastRow) 'Use the .Autofilter method to crush those 'annoying 'Thumbs.db' or 'Invoice.zip' rows Application.DisplayAlerts = False With FileRng .AutoFilter Field:=1, Criteria1:="Thumbs.db", _ Operator:=xlOr, _ Criteria2:="Invoice.zip" .Offset(1, 0).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete End With Application.DisplayAlerts = True 'Turn off the autofilter safely With Sheet2 .AutoFilterMode = False If .FilterMode = True Then .ShowAllData End If End With MsgBox "Damn son! 'Autofilter' strategy completed in " & Timer - t & " seconds." End Sub 

我录制了一个简短的截屏video,演示了这两种技术( For循环和Range.Autofilter ):

https://www.youtube.com/watch?v=1U7Ay5voVOE

希望有助于您继续开发您的脚本!