2017-03-06 65 views
0

我得到一個錯誤,我的下一個是沒有:/ 我在這裏錯過了什麼。我希望它檢查C列(單元格(y,3)),如果其空白,然後查看A列,找到G中的匹配值,然後在C列中給出F中的相應值。如果它不是空白,然後垂直移動到下一個單元格。對於迴路不完整

Dim x As Double 
    Dim y As Double 
    For y = 2 To 84212 
     For x = 531 To 632 

      If IsEmpty(Cells(y, 3)) Then 
       If Cells(y, 1).Value = Cells(x, 6).Value Then Cells(y, 3).Value = Cells(x,7).Value 
      Else: Next x 
      Else: Next y 
End Sub 
+0

我建議你使用(免費)智能壓頭:http://www.oaltd.co.uk/indenter/default.htm –

回答

1

你的循環和if語句應該是這個樣子:

Dim x As Long ' Use Long, rather than Double for integer arithmetic 
Dim y As Long 
For y = 2 To 84212 
    If IsEmpty(Cells(y, 3)) Then ' Perform this test before starting the 
           ' inner loop, thus saving 102 iterations 
     For x = 531 To 632 
      If Cells(y, 1).Value = Cells(x, 6).Value Then 
       Cells(y, 3).Value = Cells(x, 7).Value 
       Exit For ' No use looking at other "x" rows once a match has been found 
      End If 
     Next x 
    End If 
Next y 

還要注意如何縮進代碼,您可以正確地確保If語句匹配其中End IfFor語句與Next語句匹配。除了確保您的代碼有效之外,它還會使其更易於閱讀。 (請注意,我嘗試編輯你的問題來縮進代碼[我們經常做的事情是爲了讓其他人試圖回答你的問題更容易],而且沒有任何一條語句排隊 - 我最終放棄了,因爲兩個Else聲明。只有一個街區If來匹配他們)

+0

哇,謝謝,完美的工作! –

+0

也有反正,VBA本身會縮進我,而即時通訊編寫的代碼或必須手動完成嗎? –

+0

關於for循環在x上,爲什麼沒有其他的,如果它不匹配,是不是應該給一個語句然後移動到下一個x? –

0

您已經開始了兩個FOR循環,並沒有結束任何一個循環。你只要把他們放在else語句,而不是結束IF:

Dim x As Double 
Dim y As Double 
For y = 2 To 84212 
For x = 531 To 632 

If IsEmpty(Cells(y, 3)) Then 
If Cells(y, 1).Value = Cells(x, 6).Value Then Cells(y, 3).Value = Cells(x,7).Value Then 
'Do something 
End if 
End if 

Next x ' End loop with x variable 
Next y ' End loop with y variable 
     ' Both x and y can be omitted. This is just for clarifications. 
End Sub 
+0

你'如果然後 Then'聲明不起作用。 – YowE3K