除了普通的拉丁字符之外,Excel 以某種方式在各種字母表中對字串進行排序方面做得非常好。
公式中的 < 和 > 使用相同的順序。
但是 VBA 中的 < 和 > 使用不同的順序 - 可能由 Unicode() 給出。
下面的摘錄顯示了 B 列和 C 列之間的不一致。
如何使用用于排序的相同順序比較 VBA 中的字串?
我希望雖然X < Y不會給出相關結果,somefunction(X) < somefunction(Y)但會這樣做。
我發現了一些關于如何更改排序順序的文章/帖子,但這不是這里的問題。

抱歉以上是一張圖片 - 我不知道如何將 Excel 資料輸入 SO。
對于復制:
A 列中的值為: А Б В Г ? Д Е ? Ж З И 停止,從 A2 開始,命名為“第一”
B2 中=IF(A2<A3,"Less than next","Greater than next")
的公式為 D2 中的公式為=UNICODE(A2)
C 列由宏填充:
Sub Compare()
Range("first").Select
Do Until ActiveCell.Value = "Stop"
If ActiveCell.Value < ActiveCell.Offset(1, 0).Value Then
ActiveCell.Offset(0, 2).Value = "Less than next"
ElseIf ActiveCell.Value > ActiveCell.Offset(1, 0).Value Then
ActiveCell.Offset(0, 2).Value = "Greater than next"
Else
ActiveCell.Offset(0, 2).Value = "Same as next"
End If
ActiveCell.Offset(1).Select
Loop
End Sub
uj5u.com熱心網友回復:
您可以強制 VBA 在比較字串時使用不同的比較方法。
這可以為整個模塊完成,放在Option Compare Text代碼的頂部 - 如果完成,您可以使用常規比較運算子<,>而無需更改代碼(默認設定為Option Compare Binary)
您也可以使用該函式單獨進行單個比較strComp并作為第三個引數傳遞vbTextCompare(省略 tge 第三個引數將使 VBA 回退到定義的選項比較)
StrComp(cell.Value, cell.Offset(1, 0).Value, vbTextCompare)
請注意,文本排序選項還將大小寫字符視為“相等”。
不是 100% 確定這些是否總是會得到與 Excel 比較相同的結果,但至少對于您給定的示例,它確實如此。如果你不相信這一點,你可以回退到Evaluate真正使用Excel-engine 的 -method。
Option Compare Text
Sub Compare()
Dim cell As Range
Set cell = ThisWorkbook.Sheets(1).Range("A2")
Do Until cell.Value = "Stop"
Dim formula As String, res As Variant
formula = """" & cell.Value & """ < """ & cell.Offset(1, 0).Value & """"
res = Application.Evaluate(formula)
cell.Offset(0, 1) = getCmpInfostr(res)
cell.Offset(0, 2) = getCmpInfostr(cell.Value < cell.Offset(1, 0).Value)
cell.Offset(0, 3) = getCmpInfostr(StrComp(cell.Value, cell.Offset(1, 0).Value))
cell.Offset(0, 4) = getCmpInfostr(StrComp(cell.Value, cell.Offset(1, 0).Value, vbTextCompare))
Set cell = cell.Offset(1, 0)
Loop
End Sub
Function getCmpInfoString(c As Variant)
If VarType(c) = vbBoolean Then
c = IIf(c, -1, 1)
End If
If VarType(c) <> vbInteger And VarType(c) <> vbLong Then
getCmpInfostr = "invalid"
ElseIf c < 0 Then
getCmpInfostr = "Less than"
ElseIf c > 0 Then
getCmpInfostr = "Greater than"
Else
getCmpInfostr = "Same"
End If
End Function
所有 VBA 編程的強制性提示:避免Select和ActiveCell- 請參閱如何避免在 Excel VBA 中使用 Select
下面的代碼顯示了不同的方法 - 讓代碼運行一次和一次不帶Option Compare Text選項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514794.html
標籤:擅长vba排序非拉丁语
