当我尝试将一个列表合并到另一个列表时遇到问题。我目前的具体问题是它想在“CPF Derby West House”之后放置“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”时停止,而是继续 while 循环传递以下字符串“CPFFG Bungalow”和“CPHeights Bungalow”,然后最终插入“Country Way Main”之前《马丁街》
当我在 excel 中排序时,它会按照我期望的顺序放置名称。先感谢您。
最佳答案
首先,标题具有误导性,因为您没有使用 StrComp
函数 - 您正在使用比较运算符 >
.它的长短是它使用了 Option Compare
指定的比较方法。 .
我猜你没有 Option Compare
设置,所以它默认为 Option Compare Binary
.现在,考虑您在问题开头提到的 2 个字符串 CPF Derby West House
将“小于”Country Way Main
因为 'P' 的 ASCII 值是 80,而 'o' 的 ASCII 值是 111。
如果要使用不区分大小写的字符串比较,请指定 Option Compare Text
或实际使用 StrComp
函数并将其传递给 compare
vbTextCompare
的论点:
'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)
关于vba - 文本比较在 VBA 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445740/