2010-12-13 68 views
0

我有以下nexted for循环excel vba:为什么不嵌套for循环做1到多重比较?

'searches matches in Col C against B 
For Row = 2 to totalrows Step 1 

    'MsgBox "cell :" & Cells(Row, 2).Value 
    For c = 2 To totalrows Step 1 
     MsgBox " cell b :" & Cells(c, 2) & " cell C:" & Cells(rows, 3).Value 
     If Cells(c, 3).Value = Cells(Row, 2).Value Then 
      'change b color to orange = found 
      With Cells(c, 2).Interior 
       .ColorIndex = 4 
       .Pattern = xlSolid 
      End With 

     End If 

    Next c 
Next Row 

现在它比较 B1 = C1 B2 = C2 B3 = C3的 代替 B1 = C1 B1 = C2 B1 = C3 B2 = c1 b2 = c2 ...

我错过了什么吗?

+1

在msgbox中,当你得到单元格b的值时,你错过了.value,并且当你得到单元格c的值时,你写入的单元格(行,3)是错误的,应该是单元格(行,3) – BlackBear 2010-12-13 21:11:40

回答

0
Sub a() 
totalrows = 3 
'searches matches in Col C against B 
For Row = 2 To 2 + totalrows Step 1 

    'MsgBox "cell :" & Cells(Row, 2).Value 
    For c = 2 To 2 + totalrows Step 1 
     MsgBox " cell B :" & Cells(c, 2).Value & " cell C:" & Cells(Row, 3).Value 
     If Cells(c, 3).Value = Cells(Row, 2).Value Then 
      'change b color to GREEN = found 
      With Cells(c, 2).Interior 
       .ColorIndex = 4 
       .Pattern = xlSolid 
      End With 

     End If 

    Next c 
Next Row 
End Sub 
0

编辑:也许我应该提一下,msgbox中的内容和所比较的内容是不一样的,我改变了这一点。

我使用debug.print并打开即时窗口帮助。我在片

a1 b1 c1 d1 
a2 b2 c2 d2 
a3 b3 c3 d3 
a4 b4 c4 d4 

这有这样的代码

Sub mysub() 

totalrows = 4 

'searches matches in Col C against B 
For Row = 1 To totalrows Step 1 

    Debug.Print "row = " & Row 
    'MsgBox "cell :" & Cells(Row, 2).Value 
    For c = 1 To totalrows Step 1 
     'MsgBox " cell b :" & Cells(c, 2) & " cell C:" & Cells(Row, 3).Value 
     Debug.Print " cell b :" & Cells(Row, 2).Value & " cell C:" & Cells(c, 3).Value 
     If Cells(Row, 2).Value = Cells(c, 3).Value Then 
      'change b color to orange = found 
      With Cells(c, 2).Interior 
       .ColorIndex = 4 
       .Pattern = xlSolid 
      End With 

     End If 

    Next c 
Next Row 
End Sub 

这是结果

row = 1 
cell b :b1 cell C:c1 
cell b :b1 cell C:c2 
cell b :b1 cell C:c3 
cell b :b1 cell C:c4 
row = 2 
cell b :b2 cell C:c1 
cell b :b2 cell C:c2 
cell b :b2 cell C:c3 
cell b :b2 cell C:c4 
row = 3 
cell b :b3 cell C:c1 
cell b :b3 cell C:c2 
cell b :b3 cell C:c3 
cell b :b3 cell C:c4 
row = 4 
cell b :b4 cell C:c1 
cell b :b4 cell C:c2 
cell b :b4 cell C:c3 
cell b :b4 cell C:c4 
1

在MSGBOX,当你拿到小区b的值,你错过了。值,并且当你得到单元格c的值时,你写入单元格(行,3),这是错误的,应该是单元格(行,3)。 可能(因为其他人的帖子代码与您的帖子非常相似),它可以正常工作,但由于这一行代码,它显示的消息框是错误的。