使用 vbTextCompare 时 StrComp 的意外结果

Unexpected result of StrComp when using vbTextCompare

目标

按字典顺序比较两个字符串,忽略大小写。

使用 StrComp 的可能解决方案

考虑以下脚本:

val1 = "test9999"
val2 = "TEST_59895"

LexCompare val1, val2, vbBinaryCompare
LexCompare LCase(val1), LCase(val2), vbBinaryCompare
LexCompare UCase(val1), UCase(val2), vbBinaryCompare

LexCompare val1, val2, vbTextCompare
LexCompare LCase(val1), LCase(val2), vbTextCompare
LexCompare UCase(val1), UCase(val2), vbTextCompare

WScript.Echo "ANSI values: '9'=" & Asc("9") & ", '_'=" & Asc("_")

Sub LexCompare(string1, string2, compareType)
    result = ""
    Select Case StrComp(string1, string2, compareType)
        Case -1
            result = "is smaller than"
        Case 0
            result = "is identical to"
        Case 1
            result = "is greater than"
    End Select
    WScript.Echo "'" & string1 & "' " & result & " '" & string2 & "', compareType: " & compareType
End Sub

输出:

'test9999' is greater than 'TEST_59895', compareType: 0
'test9999' is smaller than 'test_59895', compareType: 0
'TEST9999' is smaller than 'TEST_59895', compareType: 0
'test9999' is greater than 'TEST_59895', compareType: 1
'test9999' is greater than 'test_59895', compareType: 1
'TEST9999' is greater than 'TEST_59895', compareType: 1
ANSI values: '9'=57, '_'=95

对我来说,“test9999”在字典序上应该小于“TEST_59895”,忽略大小写。为什么?因为'9'比'_'小。

问题

vbTextCompare 的效果是将 Option Compare Text 的规则应用于那个比较。

您可以在 documentation 中看到 Option Compare Text 不依赖于 ANSI 值,而是依赖于

case-insensitive text sort order determined by your system's locale.

您的语言环境可以指定任何排序顺序,因此 sort digits after underscores