当我尝试将一个列表合并到另一个列表时,我遇到了问题。我目前的具体问题是它想要放置" Country Way Main"之后" CPF Derby West House"。我确保两个单元格都是文本。
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到达&#34; 23&#34;在这一点上,它应该 进入这个循环:
Do While Comp_3 > Comp_4
rowidx_ma = rowidx_ma + 1
Comp_4 = Wbook(1).Worksheets("TestHistory").Cells(rowidx_ma, 4)
Loop
当Comp_3是&#34; Country Way Main&#34;和Comp_4是&#34; CPFDerby Main House&#34;相反,它继续while循环传递以下字符串&#34; CPFFG Bungalow&#34;和&#34; CPHeights Bungalow&#34;在它最终插入&#34; Country Way Main&#34;之前&#34;马丁街&#34;
当我在excel中排序时,它会按照我期望的顺序放置名称。提前谢谢。
答案 0 :(得分:5)
首先,标题具有误导性,因为您没有使用StrComp
函数 - 您正在使用比较运算符>
。它的长短是因为它使用了Option Compare
指定的比较方法。
我猜你没有Option Compare
设置,因此默认为Option Compare Binary
。现在,考虑到您在问题开头提到的2个字符串,CPF Derby West House
将小于&#34;小于&#34; Country Way Main
因为&#39; P&#39;的ASCII值是80和&#39; o&#39;的ASCII值是111。
如果要使用不区分大小写的字符串比较,请指定Option Compare Text
或实际使用 StrComp
函数,并将compare
参数传递给vbTextCompare
1}}:
'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)