For循环删除行

时间:2016-01-20 00:35:54

标签: excel vba excel-vba for-loop

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

到目前为止,我已经完成了那部分工作。我遇到的问题是,在使用这个宏的所有目录中都有不需要的文件,例如" 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",我必须运行宏两次以删除它们。显然,我想一下子把它们全部擦掉。

2 个答案:

答案 0 :(得分:5)

根据我的评论,将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

问题是,当一行被删除时,下面的一行成为该行,然后循环在它移动到下一行时跳过它。然后它也将在末尾移动空行。

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

答案 1 :(得分:3)

好问题! @Scott Craner的答案很好地解决了这个问题(upvoted顺便说一句),你最终得到了一个可读的,有效的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

希望在您继续开发脚本时有所帮助!