For 循环删除行



我正在使用一个宏,该宏列出了我选择的任何目录中的所有文件名。 我正在编写代码,将文件名分解为以后可以使用的块。 文件名列表从单元格 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

到目前为止,我已经让这部分工作正常。 我遇到的问题是,在所有误使用此宏的目录中,都有不需要的文件,例如"拇指.db"或"发票.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"的文件,则必须运行两次宏才能删除这两个宏。显然,我想一举将它们全部消灭。

根据我的评论,将 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的回答做得很好(顺便说一句),你最终会得到一个可读的、有效的 VBA 切片。好东西!

还有另一种快速删除行的方法,我认为值得一试:Range.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

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

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

希望这对您继续开发脚本有所帮助!

最新更新