1
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?

More than 1 year has passed since last update.

64bit版VBAで自然順ソート(StrCmpLogicalW )

Posted at
Option Explicit

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

Sub test()
    Dim i As Long
    Dim j As Long
    Dim tmp As String
    
    Dim ary
    ary = Array("テスト1", "ワイン", "テスト11", "テスト02", "焼酎", "ビール")
    Dim max As Long
    max = UBound(ary)

    For i = 0 To max - 1
        For j = i + 1 To max
            If StrCmpLogicalW(StrPtr(ary(j)), StrPtr(ary(i))) < 0 Then
            'If StrCmpLogicalW(StrConv(ary(j), vbUnicode), StrConv(ary(i), vbUnicode)) < 0 Then
                tmp = ary(i)
                ary(i) = ary(j)
                ary(j) = tmp
            End If
        Next j
    Next i
    
    Debug.Print Join(ary, vbLf)
End Sub

↓結果

テスト1
テスト02
テスト11
ビール
ワイン
焼酎

文字列ではなくポインタで渡すのがポイント(ポインタだけに)

よくあるパターン(コメントアウトの方)だと、以下の結果となる。

テスト1
テスト02
テスト11
ビール
焼酎
ワイン

よくある数字順に並べるパターンであれば正常に動いているように見えるが、
全角文字は化けて順序が狂う(サンプルだとワインの「ワ」が化ける)

1
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
1
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?