如何在vba中为每个循环跳转到下一次迭代?

时间:2013-06-21 17:41:28

标签: vba foreach if-statement

我从excelexperts.com获得了一个文件阅读器,其中列出了文件夹中的文件(并且可以选择包含子文件夹)。我决定调整代码以跳过“Thumbs.db”文件。

我实际上已经将代码与GoTo语句一起作为最后的手段,但我知道这被认为是错误的编程,并且想知道正确的代码是什么。

Dim iRow

Sub ListFiles()
    iRow = 11
    Call ListMyFiles(Range("C7"), Range("C8"))
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    For Each myFile In mySource.Files
        **If myFile.Name = "Thumbs.db" Then
            GoTo nextone
        Else**
            iCol = 2
            Cells(iRow, iCol).Value = myFile.Path
            iCol = iCol + 1
            Cells(iRow, iCol).Value = myFile.Name
            iCol = iCol + 1
            Cells(iRow, iCol).Value = myFile.Size
            iCol = iCol + 1
            Cells(iRow, iCol).Value = myFile.DateLastModified
            iRow = iRow + 1
        **End If**
**nextone:**
    Next
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next
    End If
End Sub

我添加的部分封装在双星中。

在我之前的尝试中,我添加了以下代码:

If myFile.Name = "Thumbs.db" Then
    Next
Else
    rest of the code here
End If

但是我得到了“Next without For”错误。这就是为什么我选择GoTo声明,我希望用更好的东西替换它。

1 个答案:

答案 0 :(得分:1)

只需将您的If语句的逻辑更改为:

For Each myFile In mySource.Files
    If myFile.Name <> "Thumbs.db" Then
        iCol = 2
        Cells(iRow, iCol).Value = myFile.Path
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Size
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.DateLastModified
        iRow = iRow + 1
    End If
Next

如果您将来有关于如何跳过文件的其他逻辑,则应将检测逻辑移至单独的方法。

For Each myFile In mySource.Files
    If ShouldProcessFile(myFile) Then
        iCol = 2
        Cells(iRow, iCol).Value = myFile.Path
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.Size
        iCol = iCol + 1
        Cells(iRow, iCol).Value = myFile.DateLastModified
        iRow = iRow + 1
    End If
Next

Function ShouldProcessFile(file)
    ShouldProcessFile = True
    If file.Name = "Thumbs.db" Then ShouldProcessFile = False
End Function