[英]Is there a better way to loop through and process files in a directory?
我有一个包含一组我希望能够处理的文件的目录。 一旦可以使用FSO对象获取文件集,就可以获取文件名,甚至可以输出到消息框。
但是,一旦我在循环中传递了每个文件的完整路径,就会遇到“ 424:需要对象”错误。 我想念什么吗? 代码中是否有些东西没有完全接受我的预期值。
任何帮助,将不胜感激。 非常感谢你。
更新 :我终于意识到我的问题归结于下面的@Dorian。 主要问题来自错误处理代码。 我通常在VBA中遇到错误处理问题。 再次感谢。
Public Sub getAllCSVFiles()
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim fileName As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(dataImportSourceLocationFolder())
On Error GoTo ErrorMessage
For Each oFile In oFolder.Files
If InStr(oFile.Name, "csv") Then
MsgBox (oFile)
fileName = oFile
If InStr(fileName, "EXTDATA1") <> 0 Then
Call loadCSVData(fileName, "EXTDATA1")
ElseIf InStr(fileName, "EXTDATA2") <> 0 Then
Call loadCSVData(fileName, "EXTDATA2")
ElseIf InStr(fileName, "EXTDATA3") <> 0 Then
Call loadCSVData(fileName, "EXTDATA3")
End If
End If
Next oFile
Application.StatusBar = "File Processing Completed"
ErrorMessage:
MsgBox Err.Source & vbCrLf & vbCrLf & Err.Description, vbCritical, "Error Importing Data"
End Sub
'This subroutine gets the csv file passed from getAllCSVs()
'
Private Sub loadCSVData(ByVal sourceFile As String, ByVal destinationWorksheet As String)
Dim destinationCell As Range
Dim destinationSheet As Excel.Worksheet
On Error GoTo errMsg
'Set destinationSheet = Worksheets("CSVDataImport") 'predefined worksheet.
Set destinationSheet = Worksheets(destinationWorksheet)
'Set destinationCell = destinationSheet.Range("A" & blankRow(destinationSheet))
Set destinationCell = destinationSheet.Range("A" & blankRow(destinationSheet))
With destinationSheet.QueryTables.Add(Connection:="TEXT;" & _
sourceFile, Destination:=destinationCell)
.FieldNames = False
.RowNumbers = False
.FieldNames = True
.RefreshOnFileOpen = False
.RefreshPeriod = 0
.TextFileStartRow = 2
.TextFileCommaDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 4, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
errMsg:
MsgBoxErr.Description , vbCritical, Err.Number
End Sub
'This function gets the first blank row in the worksheet provided by the ws Worksheet Argument
Function blankRow(ws As Worksheet) As Long
With ws
blankRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
End With
End Function
'This function gets the data location by allowing the user to select
'the location of the data files
Function dataImportSourceLocationFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select the location of the CSV Files:"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
dataImportSourceLocationFolder = sItem
Set fldr = Nothing
End Function
oFile
是Scripting.File
对象,因此您需要正确传递名称。
filename = oFile.Path
如果您设置对Windows.Scripting
的引用,则会发现更容易。
Dim oFSO as Scripting.FileSystemObject
Set oFSO = New Scripting.FileSystemObject
Dim oFile as Scripting.File
这样您便可以看到oFile对象的属性。
尝试一下,您在代码中犯了一些错误,但是现在我面临内存问题,可能是因为我没有好的.csv文件...
我正在等待您的反馈!
Public Sub getAllCSVFiles()
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim fileName As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(dataImportSourceLocationFolder())
On Error GoTo ErrorMessage
For Each oFile In oFolder.Files
Debug.Print oFile.Name
If InStr(oFile.Name, "csv") Then
MsgBox (oFile)
fileName = oFile
If InStr(fileName, "EXTDATA1") <> 0 Then
Call loadCSVData(fileName, "EXTDATA1")
ElseIf InStr(fileName, "EXTDATA2") <> 0 Then
Call loadCSVData(fileName, "EXTDATA2")
ElseIf InStr(fileName, "EXTDATA3") <> 0 Then
Call loadCSVData(fileName, "EXTDATA3")
End If
End If
Next oFile
Application.StatusBar = "File Processing Completed"
ErrorMessage:
MsgBox Err.Source & vbCrLf & vbCrLf & Err.Description, vbCritical, "Error Importing Data"
End Sub
'This subroutine gets the csv file passed from getAllCSVs()
'
Private Sub loadCSVData(ByVal sourceFile As String, ByVal destinationWorksheet As String)
Dim destinationCell As Range
Dim destinationSheet As Excel.Worksheet
'On Error GoTo errMsg
'Set destinationSheet = Worksheets("CSVDataImport") 'predefined worksheet.
Set destinationSheet = Worksheets(destinationWorksheet)
Debug.Print blankRow(destinationSheet)
Set destinationCell = destinationSheet.Range("A" & blankRow(destinationSheet))
With destinationSheet.QueryTables.Add(Connection:="TEXT;" & _
sourceFile, Destination:=destinationCell)
.FieldNames = False
.RowNumbers = False
.FieldNames = True
.RefreshOnFileOpen = False
.RefreshPeriod = 0
.TextFileStartRow = 2
.TextFileCommaDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 4, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
errMsg:
MsgBoxErr.Description , vbCritical, Err.Number
End Sub
'This function gets the first blank row in the worksheet provided by the ws Worksheet Argument
Function blankRow(ws As Worksheet) As Long
With ws
blankRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
End With
End Function
'This function gets the data location by allowing the user to select
'the location of the data files
Function dataImportSourceLocationFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select the location of the CSV Files:"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1) & "\"
End With
NextCode:
dataImportSourceLocationFolder = sItem
Set fldr = Nothing
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.