【问题标题】:Looping through and opening a directory of files with Excel VBA Dir() function quitting early使用 Excel VBA Dir() 函数提前退出循环并打开文件目录
【发布时间】:2021-10-15 18:01:35
【问题描述】:

我需要遍历一个 .csv 文件的目录,从每个文件中检索一条信息并编译成一个新的 .xlsx 文件。

Dir() 函数在遍历 500 个文件之前已经很好地退出了。


我基于此线程的解决方案:VBA code to loop through files in a folder

显然,当这个函数正在执行时,另一件事(我假设我正在编写一个 Word 文档)告诉宏在没有错误代码的情况下停止。它退出了一段时间 -> wend 循环,离开了函数访问的最后一个文档打开并且不执行 close 语句。我确认这会在没有打开任何其他内容的情况下运行宏。

如果 Dir() 函数在检查目录中的每个文件之前停止执行,请关闭其他 MicroSoft 应用程序。


到底发生了什么?有没有办法进一步缓解这个问题?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    为避免Dir 错误,请先收集文件,然后再处理它们。在致电Dir 之间不要做任何与办公室相关的事情。

    Option Explicit
    
    ' Get the files specified
    Function GetFiles(MyFolder As String) As Variant
        Dim MyFile As Variant, Files As Variant
        Dim NumFiles As Long, Idx As Long
        
        ' Collect files only and ignore folders
        MyFile = Dir(MyFolder)
        NumFiles = 0
        Do While MyFile <> ""
            NumFiles = NumFiles + 1
            If NumFiles = 1 Then
                ReDim Files(1 To 1)
            Else
                ReDim Preserve Files(1 To NumFiles)
            End If
            Files(NumFiles) = MyFile
            MyFile = Dir()
        Loop
        GetFiles = Files
    End Function
    
    Sub ProcessFiles(MyFolder As String)
        Dim MyFile As Variant
        Dim Files As Variant
        Dim Idx As Long
        
        Files = GetFiles(MyFolder)
        If Not IsEmpty(Files) Then
            For Idx = LBound(Files) To UBound(Files)
                MyFile = Files(Idx)
                ' Process the file here
                Debug.Print MyFile
            Next Idx
        Else
            Debug.Print "No files found for Dir(""" & MyFolder & """)"
        End If
    End Sub
    
    Sub TestProcessFiles()
        ProcessFiles "C:\windows\*.*"
    End Sub
    

    【讨论】:

    • 这是一个已知的错误吗?
    • @Dan 我不知道这是不是一个已知的错误。当我找到修复程序时,我没有费心去尝试追踪错误,但我怀疑处理多个办公文档可能会以某种方式重置全局环境。此外,如果您不处理错误并确保清除它们,您可能会得到未定义的行为。
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2023-03-23
    相关资源
    最近更新 更多