概要
C++ では、ソート関数が予め用意されていて、さらに、自前のカスタム比較関数を指定することで、並びをデフォルトとは違うものにすることが、比較的簡単にできます。例えば、構造体の比較関数を用意すれば、構造体の配列の並べ替えも簡単にできます。
std::sort(entries.begin(), entries.end(), compareEntriesW);
VBA では、ソート関数が用意されていないので、ワークシートを利用するか、自前で実装するなどの必要があります。
例えば、文字列を通常の並べ替えを行った場合、以下のように数字部分だけ見ると、小さい順になっていません。
Item1 Item10 Item11 Item2 Item20 Item20 Item200 Item22 Item50 Item600 Item80
これを、以下のように、数字部分が小さい順になるような並べ替えをするような実装を行います。
Item1 Item2 Item10 Item11 Item20 Item20 Item22 Item50 Item80 Item200 Item600
比較関数_StrCmpLogicalW
通常の並べ替えでは、2つの文字列変数を 比較演算子 > または、比較演算子 < を使用して比較を行いますが、今回は、StrCmpLogicalW という関数を使用します。
構文
int StrCmpLogicalW( [in] PCWSTR psz1, [in] PCWSTR psz2 );
パラメーター
[in] psz1
- 種類: PCWSTR
- 比較する最初の null で終わる文字列へのポインター。
[in] psz2
- 種類: PCWSTR
- 比較する 2 番目の null で終わる文字列へのポインター。
戻り値
文字列が同一の場合は 0 を返します。
psz1 が指す文字列の値が psz2 が指す文字列より大きい場合は、1 を返します。
psz1 が指す文字列の値が psz2 が指す値より小さい場合、-1 を返します。
注意事項
Microsoft のサイトには記載が無いようですが、psz1、psz2 の少なくともひとつにヌルポインターを渡した場合、戻り値は、 -2 が返ってきました。
VBE のイミディエイトウィンドウで実行した結果は、以下の通りです。
? StrCmpLogicalW(StrPtr(""), StrPtr("")) 0 ? StrCmpLogicalW(StrPtr(vbNullString), StrPtr("")) -2 ? StrCmpLogicalW(StrPtr(""), StrPtr(vbNullString)) -2 ? StrCmpLogicalW(StrPtr(vbNullString), StrPtr(vbNullString)) -2
そのため、
としたい場合には、StrCmpLogicalW に渡す前に、チェックが必要です。
開発環境
コード
実装には、昇順、降順の指定ができるようにしました。
関数 qSortS の第4引数 sortAsc を省略するか、True を指定すると昇順となり、False を指定すると降順となります。
サンプルデータでの実行結果
サンプルデータ
Item848 Item528 Item698 Item491 Item393 Item280 Item529 Item990 Item172 Item366 Item251 Item131 Item77 Item922 Item22 Item755 Item642 Item158 Item772 Item384
昇順で並べ替えた場合
Item22 Item77 Item131 Item158 Item172 Item251 Item280 Item366 Item384 Item393 Item491 Item528 Item529 Item642 Item698 Item755 Item772 Item848 Item922 Item990
降順で並べ替えた場合
Item990 Item922 Item848 Item772 Item755 Item698 Item642 Item529 Item528 Item491 Item393 Item384 Item366 Item280 Item251 Item172 Item158 Item131 Item77 Item22
ライセンス
- zlib ライセンス
(c) 2025 Z1000R
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
おまけ
? vbNullString = "" True ? StrPtr(vbNullString) = StrPtr("") False ? StrPtr(vbNullString) 0 ? StrPtr("") 2505097322308











