2

I'm tying to make something in VBA that will basically list all the files in one or more directories starting from a root folder. Long story short, I'm using filesystemobject to run through all of the folders and then getting all the files in those folders. Moving to the next folder, etc.

The problem I'm running into is that I need to spit out my data (onto a sheet) in the same folder sort order as one might find in Windows. I know this isn't a fixed concept per say, so here's a quick example, as it's displayed in Windows(for me):

Windows Sort Order:

FolderTest\000
FolderTest\0
FolderTest\0001

Not too surprisingly, when using FSO it returns the sub folders in a different (perhaps more logical) order:

FolderTest\0
FolderTest\000
FolderTest\0001

I was hoping someone might have an idea of what one could do to get this to be resorted as it's displaying in Windows. This is just an example obviously, the files could be named anything, but it certainly seems to behave a lot better with alpha characters in the name. I'm not necessarily married to using FSO, but I don't even know where else to look for an alternative. I know I could potentially resort these in an array, but I'm not sure what kind of wizardry would be required to make it sort in the "proper" order. For all I know, there's some method or something that makes this all better. Thanks in advance for any help!

4

2 回答 2

1

对于最终可能会提供帮助的人,以下代码看起来像是给了我正在寻找的结果,将子文件夹列表转换为您(可能)在 Windows 资源管理器中找到的相同排序顺序。从 Filesystem 对象输入子文件夹,它将结果吐出到一个数组(fnames)中。代码......它不漂亮。我会第一个承认。不要太严厉地评价我。非常感谢@Paddy(见上文)将我指向 StrCmpLogicalW(http://msdn.microsoft.com/en-us/library/windows/desktop/bb759947 (v=vs.85).aspx )

Private Declare PtrSafe Function StrCmpLogicalW Lib "shlwapi" _
(ByVal s1 As String, ByVal s2 As String) As Integer

Sub filefoldersortWindows()
Dim folder As String
Dim fnames() As String, buffer As String, content As String

folder = "Your Path"
 Set fsol = CreateObject("Scripting.fileSystemObject")
Set fold = fsol.GetFolder(folder)
FoldCount = fold.SubFolders.Count

ReDim fnames(FoldCount)
cFcount = 0
For Each fld In fold.SubFolders
    cFcount = cFcount + 1
    Namer$ = fld.Name

   fnames(cFcount) = StrConv(Namer, vbUnicode)
Next
For AName = 1 To FoldCount
    For BName = (AName + 1) To FoldCount
        If StrCmpLogicalW(fnames(AName), fnames(BName)) = 1 Then
            buffer = fnames(BName)
            fnames(BName) = fnames(AName)
            fnames(AName) = buffer
        End If
    Next
Next
For i = 1 To FoldCount
   fnames(i) = StrConv(fnames(i), vbFromUnicode)
    If i > 1 Then
    content = content & "," & fnames(i)
    Else
    content = fnames(i)
    End If
Next



End Sub
于 2013-07-09T03:25:43.833 回答
0

啊,我现在明白了。我用数字名称制作了一堆目录,看看发生了什么。Windows 资源管理器对该值进行整数转换。排序规则是这样的:

numeric value   : ascending
padding length  : descending

因此,如果有01001,都计算为整数1,但001会首先出现,因为它更长(有更多的零填充)。在这种情况下,“长度”仅指数字部分(填充),不受其后出现的任何字符的影响(它们仅在数值和填充长度相同时才重要 - 然后正常排序适用) :

资源管理器中的数字文件夹名称

于 2013-07-09T02:02:53.590 回答