2017-02-24 38 views
1

我在尝试将一个列表合并到另一个列表时出现问题。目前我的具体问题是它想在“CPF德比西屋”之后放置“Country Way Main”。我确定这两个单元格都是文本。文本比较在VBA中无法正常工作

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是“国道主”和COMP_4是“CPFDerby主屋“而是继续在”马丁街“之前插入”Country Way Main“之前通过以下字符串”CPFFG Bungalow“和”CPHeights Bungalow“的while循环

当我在Excel中排序时,按照我的名字命名我期待。先谢谢你。

回答

5

首先,标题误导您是因为您没有使用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) 
+0

我用STRCOMP调试......因为我已经从删除它说明。展望未来,我将使用StrComp与vbTextCompare。谢谢! – ezcheez

+1

@ezcheez - NP - 如果您决定选择使用Option Compare Text,我建议将该代码放在它自己的模块中,以便在不同的过程中不影响其他字符串比较。 – Comintern

相关问题