Vba 按文件名获取文件夹顺序

Vba 按文件名获取文件夹顺序,vba,excel,Vba,Excel,这是我用于合并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 = Create

这是我用于合并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

@AFischbein认为VBA中没有集合、数组、字典等的内置排序是正确的。但是,我最近了解了
System.Collections.ArrayList
,它有一个内置的排序方法,可以用于一维数组

您可以自己尝试以下示例:

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
在您的示例中,可能类似(未经测试):


有一种非常非常快速的方法可以从目录中获取排序文件数组

Sub SortDirectoryAscending()

    Dim r() As String

    r = Filter(Split(CreateObject("wscript.shell").exec _
                 ("cmd /c Dir ""C:\test\"" /b /a-d /on") _
                 .stdout.readall, vbCrLf), ".")

   For Each file_ In r
     MsgBox (file_)
   Next file_

End Sub

VBA中没有对集合排序的内置支持。您可以选择(a)编写(或复制)VBA排序算法,(2)使用临时工作表使用Excel函数进行排序,(3)填充记录集并使用排序属性。(a) 将可能是最好的性能,但也是最前期的工作,(b)可能是最简单的,但可能有副作用的工作手册,(c)是快速排序,我用了很多。
Sub SortDirectoryAscending()

    Dim r() As String

    r = Filter(Split(CreateObject("wscript.shell").exec _
                 ("cmd /c Dir ""C:\test\"" /b /a-d /on") _
                 .stdout.readall, vbCrLf), ".")

   For Each file_ In r
     MsgBox (file_)
   Next file_

End Sub