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

时间:2019-07-23 09:26:25

标签: excel vba

我有一个目录,其中包含一组我希望能够处理的文件。一旦可以使用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

2 个答案:

答案 0 :(得分:0)

oFileScripting.File对象,因此您需要正确传递名称。

filename = oFile.Path

如果将引用设置为Windows.Scripting然后

,您会发现更加容易
Dim oFSO as Scripting.FileSystemObject
Set oFSO = New Scripting.FileSystemObject
Dim oFile as Scripting.File

然后您将能够看到oFile对象的属性。

答案 1 :(得分:0)

尝试一下,您在代码中犯了一些错误,但是现在我遇到了内存的问题,也许是因为我没有好的.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