Dir 循环缺少指定文件夹中的一个文件

Dir loop missing one file in specified folder

我写了一个宏来处理指定文件夹中所有文件中的数据。但是,它会跳过文件夹中的第一个文件。问题是第一个文件在这一行被引用:

FileName = Dir(path)

但是下一个文件是用这一行引用的:

FileName = Dir()

完整代码:

Sub data_gatherer() 'skips ESAM_50

    'Removes unrealistic data and sums the no. starts/hours run for each pump stream
    Application.ScreenUpdating = False

        Dim sheet As Worksheet
        Dim calcSheet As Worksheet
        Dim path As String
        Dim ColCount As Integer
        Dim StreamCode As String
        Dim StreamSum As Double
        Dim NextRow As Double
        Dim FilePath As String
        Dim FileName As String
        Dim i As Integer
        Dim SumRange As range
        Dim SheetName As String
        Dim sSrcFolder As String

        sSrcFolder = "C:\IRIS MACRO TEST ZONE\SPS IRIS Bulk Data\" ' unprocessed data

        path = sSrcFolder & "*.csv" 'files withing sSrcFolder
        FileName = Dir(path)


        Do While FileName <> ""

            FileName = Dir() '''''skips first file here'''''''''''''''''''''''''''''''''''''''''''''''
            FilePath = sSrcFolder & FileName

                If FilePath = "C:\IRIS MACRO TEST ZONE\SPS IRIS Bulk Data\" Then ''' avoids error message for " .csv"
                    Exit Do
                End If

                Workbooks.Open (FilePath) 'error here - looks for "" filename

            SheetName = Left(FileName, 10)

                With Workbooks(FileName).Sheets(SheetName)
                    ColCount = .Cells(3, .Columns.count).End(xlToLeft).Column 'COUNT COLUMNS WITH DATA need to start with col 2
                    For i = 2 To ColCount 'i=2 to avoid date column

                            Call data_cleaner_all(FileName, SheetName, i)
                            Call StreamCalcs(NextRow, FileName, SheetName, SumRange, i)

                    Next i

                End With

             Workbooks(FileName).Saved = True
             Workbooks(FileName).Close
        Loop

    Application.ScreenUpdating = True

    End Sub

FileName = Dir() 放在循环的 end 处,直接在

之前
Loop

行。

编辑回复:

What is the difference in meaning between FileName = Dir() and FileName = Dir(path) ?

Dir(path)初始化Dir函数,returns第一个file/folder名字。 Dir() 始终是对之前 Dir(path) 的后续调用,returns 是下一个 file/folder.

如果您在之前未调用 Dir(path) 的情况下调用 Dir(),则会出现运行时错误。