【发布时间】: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 来获取其他参数。