简体   繁体   English

有没有更好的方法来遍历和处理目录中的文件?

[英]Is there a better way to loop through and process files in a directory?

I have a directory with a set of files that I want to be able to process. 我有一个包含一组我希望能够处理的文件的目录。 Once I'm able to acquire the file set using an FSO object, I can get the file names and can even output to a message box. 一旦可以使用FSO对象获取文件集,就可以获取文件名,甚至可以输出到消息框。

Once I pass the full path of each file in the loop however, I run into a '424: Object required' error. 但是,一旦我在循环中传递了每个文件的完整路径,就会遇到“ 424:需要对象”错误。 Am I missing something? 我想念什么吗? Is there something within the code that's not quite accepting the value as I intended. 代码中是否有些东西没有完全接受我的预期值。

Any help in this would be appreciated. 任何帮助,将不胜感激。 Thank you very much. 非常感谢你。

UPDATE : I finally realized where my problem was thanks to @Dorian below. 更新 :我终于意识到我的问题归结于下面的@Dorian。 The main issue stemmed from the error handling code. 主要问题来自错误处理代码。 I have issues with error handling in general in VBA. 我通常在VBA中遇到错误处理问题。 Thanks again. 再次感谢。

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 is a Scripting.File object so you need to pass the name properly. oFileScripting.File对象,因此您需要正确传递名称。

filename = oFile.Path

You will find it easier if you set a reference to Windows.Scripting then 如果您设置对Windows.Scripting的引用,则会发现更容易。

Dim oFSO as Scripting.FileSystemObject
Set oFSO = New Scripting.FileSystemObject
Dim oFile as Scripting.File

As you would then be able to see the properties of the oFile object. 这样您便可以看到oFile对象的属性。

Give this a try , you did some mistake in code but now I am facing the issue with memory maybe it's because I don't have the good .csv file... 尝试一下,您在代码中犯了一些错误,但是现在我面临内存问题,可能是因为我没有好的.csv文件...

I am waiting for your feedbacks ! 我正在等待您的反馈!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM