vba循环遍历文件夹中的新文件

时间:2015-11-11 12:02:19

标签: excel-vba vba excel

我有一个文件夹,其中下载了来自FTP服务器的CSV文件,我需要打开最新的文件并从中提取数据。我这样做是对比来自文本连接的get数据。问题是该文件夹有15000多个文件,我只需打开上周的文件,也许是100个文件。 有没有办法按特定顺序打开它们?然后我可以说时间戳文件<然后一段时间 - >停止循环。

THX!

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助。它是我的改造项目。重要的是,您要写入要从中过滤文件的日期(5,1)。例如,如果您放置11.11.2015,则只显示小于该文件的文件,因此不会记录任何文件。但是如果你将1.1.1914放在单元格5,1中,那么所有文件都会弹出。我不知道你打开哪个文件。你没有意思类型所以我没有把workbook.open放到代码中,但我在代码中放了一个注释,其中应该发生一些开放。所以根据您的需要编辑我的代码。

Private Sub CommandButton1_Click()
ThisWorkbook.Save
DoEvents
Const ROW_FIRST As Integer = 2
Dim intResult As Integer
Dim strPath As String
Dim objFSO As Object
Dim intCountRows As Integer

Application.FileDialog(msoFileDialogFolderPicker).Title = "Vyberte prosím složku"
Application.FileDialog(msoFileDialogFolderPicker).ButtonName = "Vybrat složku"
Application.FileDialog(msoFileDialogFolderPicker).AllowMultiSelect = True

intResult = Application.FileDialog(msoFileDialogFolderPicker).Show

For Each Item In Application.FileDialog(msoFileDialogFolderPicker).SelectedItems
    If intResult <> 0 Then
        Application.ScreenUpdating = False
        Range("A:A").ClearContents
        Range("B:B").ClearContents
        Range("C:C").ClearContents
        Cells(1, 1).Value = "NAME"
        Cells(1, 2).Value = "PATH"
        Cells(1, 3).Value = "TAIL"
        Cells(1, 4).Value = "Last check:"

        strPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)

        Set objFSO = CreateObject("Scripting.FileSystemObject")

        intCountRows = GetAllFiles(strPath, ROW_FIRST, objFSO)
        Call GetAllFolders(strPath, objFSO, intCountRows)
        Application.ScreenUpdating = True
    End If
Next Item
Cells(1, 5).Value = Date
End Sub

Private Function GetAllFiles(ByVal strPath As String, ByVal intRow As Integer, ByRef objFSO As Object) As Integer
DoEvents
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
i = intRow - ROW_FIRST + 1
Set objFolder = objFSO.GetFolder(strPath)

For Each objFile In objFolder.Files
    inte = InStr(1, objFile.Name, "prázdný")
        If objFile.datecreated > DateValue(Cells(1, 5).Value) Then
'HERE SHOULD BE THE OPENING PROCEDURE!!!!!!!!!!!!!!                
                Cells(i + ROW_FIRST - 1, 1) = objFile.Name
                Cells(i + ROW_FIRST - 1, 2) = objFile.Path
                Cells(i + ROW_FIRST - 1, 3) = Right(objFile.Name, Len(objFile.Name) - InStrRev(objFile.Name, "."))
                i = i + 1
        End If
Next objFile
GetAllFiles = i + ROW_FIRST - 1

End Function

Private Sub GetAllFolders(ByVal strFolder As String, ByRef objFSO As Object, ByRef intRow As Integer)
DoEvents
Dim objFolder As Object
Dim objSubFolder As Object
Static veSpravneSlozce As Boolean

Set objFolder = objFSO.GetFolder(strFolder)
For Each objSubFolder In objFolder.subfolders
        intRow = GetAllFiles(objSubFolder.Path, intRow, objFSO)
        Call GetAllFolders(objSubFolder.Path, objFSO, intRow)
Next objSubFolder
End Sub

开放程序应该在中间子