按文件名获取文件夹顺序

这是我的合并XML的VB代码,但我想通过文件名合并它。 所以先1.xsl然后2.xsl

如何在VB中下单?

Sub simpleXlsMerger() 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("D:\change\to\excel\files\path\here") Set filesObj = dirObj.Files For Each everyObj In filesObj Set bookList = Workbooks.Open(everyObj) 'change "A2" with cell reference of start point for every files here 'for example "B3:IV" to merge all files start from columns B and rows 3 'If you're files using more than IV column, change it to the latest column 'Also change "A" column on "A65536" to the same column as start point Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy ThisWorkbook.Worksheets(1).Activate 'Do not change the following column. It's not the same column as above Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial Application.CutCopyMode = False bookList.Close Next End Sub 

从目录中获取sorting文件数组的确有一个非常快的方法。

 Sub SortDirectoryAscending() Dim r() As String r = Filter(Split(CreateObject("wscript.shell").exec _ ("cmd /c Dir ""C:\test\"" /b /ad /on") _ .stdout.readall, vbCrLf), ".") For Each file_ In r MsgBox (file_) Next file_ End Sub 

@AFischbein是正确的,没有在VBA中的集合,数组,字典等内置sorting。 不过,我最近了解到System.Collections.ArrayList有一个内置的sorting方法,这将适用于一维数组。

你可以尝试一下这个例子:

 Sub test() Dim list As Object Dim i as Integer Dim arr As Variant arr = Array(99, 25, 37, 3, 29, 33, 4, 105, 1) Set list = CreateObject("System.Collections.Arraylist") For i = LBound(arr) To UBound(arr) list.Add arr(i) Next list.Sort arr = list.ToArray() End Sub 

在你的例子中,也许像(未经testing):

 Dim list As Object Dim listItem as Variant Dim bookList as Workbook 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("D:\change\to\excel\files\path\here") Set filesObj = dirObj.Files Set list = CreateObject("System.Collections.Arraylist") '## Store the names in an ArrayList For Each everyObj In filesObj list.Add everyObj Next '## Sort the list (ascending) list.Sort '## Optionally, sort it descending: 'list.Reverse For each listItem in list.ToArray() Set bookList = Workbooks.Open(listItem) '## The rest of your code goes here... bookList.ActiveSheet.Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy ThisWorkbook.Worksheets(1).Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial Application.CutCopyMode = False bookList.Close ' Next