这是我用于合并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
答案 0 :(得分:1)
从目录中获取一系列已排序文件的确有一种非常快速的方法。
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
答案 1 :(得分:0)
@AFischbein是正确的,VBA中没有集合,数组,字典等的内置排序。但是,我最近了解了{em> 具有内置排序方法的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
在你的例子中,可能是(未经测试的):
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