文本比较在VBA中无法正常工作

当我尝试将一个列表合并到另一个列表中时遇到问题。 我现在的具体问题是想要在“CPF德比西屋”之后放置“Country Way Main”。 我已经确定这两个单元格都是文本。

lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row rowidx_mo = 2 rowidx_ma = 2 For rowidx_mo = 2 To lastRow Comp_1 = ActiveSheet.Cells(rowidx_mo, 5) Comp_2 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 5) Comp_3 = ActiveSheet.Cells(rowidx_mo, 4) Comp_4 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 4) Do While Comp_1 > Comp_2 rowidx_ma = rowidx_ma + 1 Comp_2 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 5) Comp_4 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 4) Loop If (Comp_1 < Comp_2) Then 'insert test into aggregate Range(Cells(rowidx_mo, 1), Cells(rowidx_mo, 9)).Select Selection.Cut Wbook(1).Activate Range(Cells(rowidx_ma, 1), Cells(rowidx_ma, 9)).Select Selection.Insert Shift:=xlDown ElseIf (Comp_1 = Comp_2) Then Do While Comp_3 > Comp_4 rowidx_ma = rowidx_ma + 1 Comp_4 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 4) Loop If (Comp_3 < Comp_4) Then 'test exists in aggregate, but not specific location Range(Cells(rowidx_mo, 1), Cells(rowidx_mo, 9)).Select Selection.Cut Wbook(1).Activate Range(Cells(rowidx_ma, 1), Cells(rowidx_ma, 9)).Select Selection.Insert Shift:=xlDown ElseIf (Comp_3 = Comp_4) Then Cells(rowidx_mo, 9).Select Selection.Cut Wbook(1).Activate Cells(rowidx_ma, 10).Select Selection.Insert End If End If rowidx_ma = rowidx_ma + 1 Wbook(2).Activate Next 

代码正常工作,直到rowidx_mo达到“23”在这一点上,它应该进入这个循环:

 Do While Comp_3 > Comp_4 rowidx_ma = rowidx_ma + 1 Comp_4 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 4) Loop 

当Comp_3是“Country Way Main”,Comp_4是“CPFDerby Main House”时停止,而是继续通过以下string“CPFFG Bungalow”和“CPHeights Bungalow”的while循环,最后插入“Country Way Main” “马丁街”

当我在excel中sorting时,它按照我所期望的顺序排列名称。 先谢谢你。

首先,标题是误导的,因为你没有使用StrComp函数 – 你正在使用比较运算符> 。 它的长短之处在于它使用了Option Compare指定的比较方法。

我猜你没有Option Compare 设置 ,所以它是默认Option Compare Binary 。 现在,考虑到您在问题开始时提到的两个string, CPF Derby West House将会“小于” Country Way Main因为“P”的ASCII值是80,“o”的ASCII值是111。

如果要使用不区分大小写的string比较,请指定Option Compare Text或实际使用 StrComp函数,并将其传递给vbTextComparecompare参数:

 'Returns 1, because with text comparison, the first string is greater than the second. Debug.Print StrComp("CPF Derby West House", "Country Way Main", vbTextCompare)