VBA按文件名中的日期顺序打开文件?

时间:2015-06-30 11:53:33

标签: vba date merge

我现在所拥有的:

Sub Merge()Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
    Application.ScreenUpdating = False
    Set mergeObj = CreateObject("Scripting.FileSystemObject")

    'change folder path of excel files here
    Set dirObj = mergeObj.Getfolder("G:\loc\loc\loc\loc\loc\loc\loc")
    Set filesObj = dirObj.Files
    For Each everyObj In filesObj
        Set bookList = Workbooks.Open(everyObj)

        Range("A4:I" & Range("A65536").End(xlUp).Row).Copy
        ThisWorkbook.Worksheets(1).Activate

        Range("B65536").End(xlUp).Offset(0, 0).PasteSpecial
        Application.CutCopyMode = False
        bookList.Close
    Next
End Sub

我想更改此内容,以便按日期顺序打开并复制文件(包含在文件名中)

例如,它会按照以下顺序打开并复制:

“20150601 - Daily Update.xls”
“20150602 - 每日更新.xls”
“20150603 - 每日更新.xls”

1 个答案:

答案 0 :(得分:0)

我已将用户@LocEngineer注释中引用的用户@Papasmile的排序解决方案与您的代码(所有信用)合并在一起:

Sub Merge()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object
Dim filesObj As Object, everyObj As Object, outputLines As Object
Dim outputLine
    Application.ScreenUpdating = False
    Set mergeObj = CreateObject("Scripting.FileSystemObject")
    Set outputLines = CreateObject("System.Collections.ArrayList")

    'change folder path of excel files here
    Set dirObj = mergeObj.Getfolder("G:\loc\loc\loc\loc\loc\loc\loc")
    Set filesObj = dirObj.Files
    For Each everyObj In filesObj
        outputLines.Add everyObj.Name
    Next
    outputLines.Sort

    For Each outputLine In outputLines
        Set bookList = Workbooks.Open(outputLine)

        Range("A4:I" & Range("A65536").End(xlUp).Row).Copy
        ThisWorkbook.Worksheets(1).Activate

        Range("B65536").End(xlUp).Offset(0, 0).PasteSpecial
        Application.CutCopyMode = False
        bookList.Close
    Next
End Sub