0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EXCEL VBA エクスプローラと同じソート

Posted at

プログラム

FileSystemObject オブジェクトで取得したファイル名をエクスプローラと同じ順序でソートします。

ファイルは "D:\Temp" フォルダにあると仮定します。
File_A1.txt
File_A2.txt
File_A10.txt

ファイル名は Collection オブジェクトに格納してソートします。

' 32 bit
Private Declare Function StrCmpLogicalW Lib "SHLWAPI.DLL" (ByVal lpStr1 As Long, ByVal lpStr2 As Long) As Long
' 64 bit
' Private Declare PtrSafe Function StrCmpLogicalW Lib "SHLWAPI.DLL" (ByVal lpStr1 As LongPtr, ByVal lpStr2 As LongPtr) As Long

Private Sub 作成ファイル一覧()
    Dim fso As New Scripting.FileSystemObject
    Dim fdo As Scripting.Folder
    Dim flo As Scripting.File
    Dim strFolder As String
    Dim colファイル一覧 As New Collection
    Dim intIA() As Integer
    Dim i As Integer
    
    Debug.Print "開始"
    strFolder = "D:\Temp"
    Set fdo = fso.GetFolder(strFolder)
    For Each flo In fdo.Files
        colファイル一覧.Add flo.Name
    Next

    Debug.Print "ソート前"
    ReDim intIA(colファイル一覧.Count - 1)
    For i = 0 To UBound(intIA)
        intIA(i) = i + 1
        Debug.Print colファイル一覧(intIA(i))
    Next i

    自然順ソート intIA, colファイル一覧

    Debug.Print "ソート後"
    For i = 0 To UBound(intIA)
        Debug.Print colファイル一覧(intIA(i))
    Next
End Sub

Private Sub 自然順ソート(intIA() As Integer, colファイル一覧 As Collection)
    Dim i, j, max, tmp As Integer
    
    max = UBound(intIA)
    For i = 0 To max - 1
        For j = i + 1 To max
            If StrCmpLogicalW(StrPtr(colファイル一覧(intIA(i))), StrPtr(colファイル一覧(intIA(j)))) > 0 Then
                tmp = intIA(i): intIA(i) = intIA(j): intIA(j) = tmp
            End If
        Next j
    Next i
End Sub

結果

開始
ソート前
FILE_A1.txt
FILE_A10.txt
FILE_A2.txt
ソート後
FILE_A1.txt
FILE_A2.txt
FILE_A10.txt
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?