2015-05-14 32 views
2

我有以下代碼,它適用於列中的第一個值,但我需要修改代碼,以便它將if語句應用於列中的所有值。現在它將結果作爲40列的K列中的所有值,但我需要代碼運行,以便它首先評估K2,然後K3,然後K4等請幫助!如何將宏應用於所有行?

Sub UPTRange() 



Dim UPT As Range, cell As Range, result As Range 
Set UPT = Range("K2:K2642") 
Set result = Range("L2:L2642") 

For Each cell In UPT 

If cell.Value >= 40 Then 
result = "40 +" 
ElseIf cell.Value = (30 <= 39) Then 
result = "30 - 39" 
ElseIf cell.Value = (20 <= 29) Then 
result = "20 - 29" 
ElseIf cell.Value = (10 <= 19) Then 
result = "10 - 19" 
ElseIf cell.Value = (2 <= 9) Then 
result = "2 - 9" 
ElseIf cell.Value = (0 <= 1) Then 
result = "0 - 1" 
Else: cell.Value = "Error" 
End If 

Next 

For Each cell In result 

Range("L2").Value = result 
Next 


End Sub 

回答

3
If cell.Value = (30 <= 39) Then 

相同

If cell.Value = True Then 

因爲你正在評估表達30 <= 39,這給True ...

如果你想檢查的範圍,那麼你應該使用類似

If cell.Value > 30 And cell.Value <= 39 Then 

一旦你有了result值則只是這樣做:

cell.offset(0, 1).Value = result 

result一個細胞地方的cell

編輯

Sub UPTRange() 

    Dim UPT As Range, cell As Range, result, v 

    Set UPT = ActiveSheet.Range("K2:K2642") 

    For Each cell In UPT 

    v=cell.value 

    If v >= 40 Then 
     result = "40 +" 
    ElseIf v > 30 And v <= 39) Then 
     result = "30 - 39" 
    ElseIf 
     'etc etc 
    Else 
     result = "Error" 
    End If 

    cell.Offset(0, 1).Value = result 

    Next 

End Sub 
+0

嗨。感謝您的反饋,但我不認爲這確實解決了問題。我能夠得到一個結果到我需要的單元格中,但公式看起來並沒有循環遍歷k列中的所有單元格。你知道一個辦法嗎? – Gabi

+0

看我上面的編輯 –

0

也許這正確的?

If cell.Value >= 40 Then 
    cell.Formula = "40 +" 
ElseIf cell.Value >= 10 And cell.Value < 40 Then 
    cell.Formula = (Int(cell.Value/10) * 10) & " - " & (Int(cell.Value/10) * 10) + 9 
ElseIf cell.Value > 1 And cell.Value < 10 Then 
    cell.Formula = "2 - 9" 
Else 
    cell.Formula = "Error" 
End If 
相關問題