1

我从 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 语句,我希望用更好的东西来代替它。

4

1 回答 1

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
于 2013-06-21T17:55:45.273 回答