Dir循环丢失指定文件夹中的一个文件

时间:2015-11-12 13:11:01

标签: excel vba excel-vba dir

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

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

1 个答案:

答案 0 :(得分:4)

FileName = Dir()放在循环的结尾,直接放在

之前
Loop

线。

修改

  

FileName = Dir()FileName = Dir(path)之间的含义有何不同?

Dir(path)初始化Dir函数,并返回第一个文件/文件夹名称。 Dir()始终是之前发送的Dir(path)的后续调用,并返回下一个文件/文件夹。

如果您之前未调用Dir()而致电Dir(path),则会收到运行时错误。