【问题标题】:Dir loop missing one file in specified folder目录循环在指定文件夹中缺少一个文件
【发布时间】:2015-11-12 13:11:01
【问题描述】:

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

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() 行移到Loop 行之前。
  • 太好了,谢谢@Vincent G。FileName = Dir() FileName = Dir(path) 之间的含义有什么区别
  • Dir(Path) 返回路径对应的第一个文件名。您可以通过使用空字符串参数或不带参数调用 Dir 来获取其他参数。

标签: vba excel dir


【解决方案1】:

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

之前
Loop

行。

编辑回复:

FileName = Dir()FileName = Dir(path) 的含义有什么区别?

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

如果您调用 Dir() 之前没有调用过 Dir(path),则会出现运行时错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-11
    • 2021-03-02
    • 2016-05-28
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2012-12-24
    相关资源
    最近更新 更多