自然順とは
自然順とは数字に見えるものは数字として並べた順です。
具体的にはエクスプローラーで名前順にした時の順です。
通常、文字列をソートすると文字コード順になりますが、Windows APIを使う事で自然順にする事が出来ます。
サンプルコード
C#
//Array.Sort(strArray, new LogicalStringComparer());でstrArrayをソート
public class LogicalStringComparer : IComparer, IComparer<string>
{
[System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(string x, string y);
public int Compare(string x, string y)
{
return StrCmpLogicalW(x, y);
}
public int Compare(object x, object y)
{
return Compare(x.ToString(), y.ToString());
}
}
VBA
'LetsSort(strArray)でstrArrayをソート
Declare PtrSafe Function StrCmpLogicalW Lib "SHLWAPI.DLL" (ByVal lpStr1 As String, ByVal lpStr2 As String) As Long
Public Sub LetsSort(ByRef arrayToSort() As String)
Dim i As Long
Dim j As Long
Dim temp As String
For i = LBound(arrayToSort) To UBound(arrayToSort)
For j = i To UBound(arrayToSort)
If StrCmpLogicalW(StrConv(arrayToSort(i), vbUnicode), StrConv(arrayToSort(j), vbUnicode)) > 0 Then
temp = arrayToSort(i)
arrayToSort(i) = arrayToSort(j)
arrayToSort(j) = temp
End If
Next j
Next i
End Sub