【问题标题】:VBA loop through files in a folder not working properlyVBA循环浏览文件夹中的文件无法正常工作
【发布时间】:2021-05-02 07:38:23
【问题描述】:

以下代码有 2 个问题。

  1. 在第一个循环中它找到了相同的文件,因此如果文件名称相同,我为什么要跳过它。之后,它将按应有的方式进行。在第 3 次循环中,而不是找到第 3 个文件 (fileName2 = Dir) 变为 fileName2 = ""。
  2. 当我希望 fileName 转到第二个文件 (fileName = Dir) 时,出现运行时 5 错误。

*注意:我目前正在测试的文件夹中有 6 个文件,但我希望将其用于包含 10,000 个小文件的文件夹

    Sub TestMD5()
   Dim myfilepath As String
   Dim myfilepath2 As String
   Dim fileName As Variant
   Dim fileName2 As Variant
   Dim fldr As FileDialog
   Dim sItem As String


   Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
   With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = Application.DefaultFilePath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
   End With
   NextCode:
   GetFolder = sItem & "\"
   Set fldr = Nothing



   fileName = Dir(GetFolder)
   fileName2 = Dir(GetFolder)

   Do While fileName <> ""
    Do While fileName2 <> ""



   myfilepath = GetFolder & fileName
   myfilepath2 = GetFolder & fileName2

   If myfilepath <> myfilepath2 Then

   If FileToMD5Hex(myfilepath) = FileToMD5Hex2(myfilepath2) And FileToSHA1Hex(myfilepath) = 
   FileToSHA1Hex2(myfilepath2) Then
    'Kill (myfilepath2)
    Debug.Print "match - " & (fileName) & " & " & (fileName2)
   Else
   Debug.Print "no match - " & (fileName) & " & " & (fileName2)
   End If

   End If
        fileName2 = Dir
    Loop
    
   'Set the fileName to the next file
   fileName = Dir
   Loop

   End Sub

【问题讨论】:

  • 它被认为是相同的Dir,并且每当你在它没有返回后再次调用它时,你都会得到这个错误。

标签: excel vba


【解决方案1】:

我将您的代码与“文件系统对象”方法混合在一起,我们可以在其中对文件执行For each 循环。
这至少让您远离整个运行时 5 错误。也许有用。

Sub TestMD5()
Dim myfilepath As Variant, myfilepath2 As Variant
Dim sItem As String
Dim fso As Object
Dim fldr As Variant
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = Application.DefaultFilePath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
End With
NextCode:

Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(sItem & "\")

For Each myfilepath In fldr.Files
    For Each myfilepath2 In fldr.Files
    If Not myfilepath = myfilepath2 Then
        If FileToMD5Hex(myfilepath) = FileToMD5Hex2(myfilepath2) And FileToSHA1Hex(myfilepath) = FileToSHA1Hex2(myfilepath2) Then
            'Kill (myfilepath2)
            Debug.Print "match - " & (myfilepath) & " & " & (myfilepath2)
        Else
            Debug.Print "no match - " & (myfilepath) & " & " & (myfilepath2)
        End If
    End If
    Next myfilepath2
Next myfilepath

End Sub

【讨论】:

  • 感谢完美。现在可以理解为什么它没有按照我尝试编写的方式工作。
【解决方案2】:

我认为应该使用 FileDialog(msoFileDialogFilePicker) 而不是 FileDialog(msoFileDialogFolderPicker)

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 2012-05-09
    • 1970-01-01
    • 2018-06-04
    • 2018-05-27
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多