有没有办法在VBA中获取文件夹文件名的排序列表?到目前为止,我到了
Dim fso As Object
Dim objFolder As Object
Dim objFileList As Object
Dim vFile As Variant
Dim sFolder As String
sFolder = "C:\Docs"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(sFolder)
Set objFileList = objFolder.Files
For Each vFile In objFileList
' do something '
Next vFile
但确保for循环的处理顺序由文件名确定...
至关重要任何帮助表示赞赏!
答案 0 :(得分:3)
下载VBA排序例程,例如:Recursive Quick Sort
使用文件名填充数组,并按照here显示排序。
答案 1 :(得分:1)
看起来您可以使用ADODB.RecordSet
来完成此操作。这有点重,但here'是一个可以帮助你入门的参考。
答案 2 :(得分:1)
订单是任意的。
当你走过objFileList
时,将文件添加到数组中,然后sort the array。
答案 3 :(得分:1)
由于仅链接答案的数量很多,包括接受的答案,我将发布一个经过测试的快速排序功能示例,该示例应用于 FSO 文件集合。 QuickSort
将适用于任何字符串数组。我从 the link posted by Mitch Wheat in the accepted answer 获取代码并清理它。
Option Explicit
' Return an array containing the names of the
' files in the directory sorted alphabetically.
Public Function SortedFiles(ByVal dirPath As String) As String()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim listFolder As Object
Set listFolder = fso.GetFolder(dirPath)
' Make the list of names.
Dim fileCount As Long
fileCount = listFolder.Files.Count
Dim fileNames() As String
ReDim fileNames(1 To fileCount)
Dim i As Long
i = 1
Dim thisFile As Object
For Each thisFile In listFolder.Files
fileNames(i) = thisFile.Name
i = i + 1
Next thisFile
' Return the sorted list.
SortedFiles = QuickSort(fileNames, 1, fileCount)
End Function
' Use Quicksort to sort a list of strings.
'
' This code is from the book "Ready-to-Run
' Visual Basic Algorithms" by Rod Stephens.
' http://www.vb-helper.com/vba.htm
Public Function QuickSort(ByVal list As Variant, ByVal min As Long, ByVal max As Long) As String()
Dim midValue As String
Dim high As Long
Dim low As Long
Dim i As Long
Dim newList() As String
newList = list
' If there is 0 or 1 item in the list,
' this sublist is sorted.
If Not min >= max Then
' Pick a dividing value.
i = Int((max - min + 1) * Rnd + min)
midValue = newList(i)
' Swap the dividing value to the front.
newList(i) = newList(min)
low = min
high = max
Do
' Look down from hi for a value < mid_value.
Do While newList(high) >= midValue
high = high - 1
If high <= low Then Exit Do
Loop
If high <= low Then
newList(low) = midValue
Exit Do
End If
' Swap the lo and hi values.
newList(low) = newList(high)
' Look up from lo for a value >= mid_value.
low = low + 1
Do While newList(low) < midValue
low = low + 1
If low >= high Then Exit Do
Loop
If low >= high Then
low = high
newList(high) = midValue
Exit Do
End If
' Swap the lo and hi values.
newList(high) = newList(low)
Loop
' Sort the two sublists.
newList = QuickSort(newList, min, low - 1)
newList = QuickSort(newList, low + 1, max)
End If
QuickSort = newList
End Function