2010-12-13 21 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)。 可能(因爲其他人的帖子代碼與您的帖子非常相似),它可以正常工作,但由於這一行代碼,它顯示的消息框是錯誤的。