2013-06-03 85 views
3

我有一段代碼,它取得單元格中的值並根據值設置不同的單元格。這是一個簡單的代碼,我只是無法弄清楚如何循環遍歷整個列。有人能指導我如何做到這一點嗎?提前致謝!VBA循環遍歷列中的值並根據值更改下一列

這裏是我的代碼:

Dim pH As Single, Program As String 
pH = Range("D2").Value 

If pH <= 7.8 Then 
    Program = "Neutral" 
Else 
    Program = "Alkaline" 

Range("E2").Value = Program 

回答

3

如果你想在VBA中這樣做,你可以創建一個'Do Until'循環直到列中沒有更多值:

Sub Looper() 

Dim i as Integer 
Dim Sel as String 
Dim MoveDown as String 
Dim pH as Single 
Dim Program as String 

i = 2 
MoveDown = "YES" 

Do Until MoveDown = "DONE" 
    Sel = "D" + Replace(Str(i), " ", "") 
    ph = Range(Sel).Value 

    If pH <= 7.8 Then 
     Program = "Neutral" 
    Else 
     Program = "Alkaline" 
    End If 

    Sel = "E" + Replace(Str(i), " ", "") 
    Range(Sel).Value = Program 
    i = i + 1 
    Sel = "D" + Replace(Str(i), " ", "") 
    If Range(Sel).Value = "" Then 
     MoveDown = "DONE" 
    End If 
Loop 
End Sub 
+0

這太好了。奇蹟般有效。謝謝 – mad5245

6

你不需要VBA尚未

一套公式中的E2 '= IIF(D2<=7.8;"Neutral";"Alkaline")'

而且你可以把它複製到下面列E到列

+0

我打算讓它做得更多。這只是一個開始。儘管謝謝你的迴應。 – mad5245

+2

我的代碼基於你的問題..更好地提及你所需要的所有 – matzone

2

這可能使用是最佳的解決方案VBA:

Sub mysub() 

    Set Wksht = ThisWorkbook.Sheets("Sheet1") 'the Worksheet name you want to fetch data from 
    Wksht.Select 
    Set myRange = Wksht.Range("D2", Range("D65536").End(xlUp)) 

    For Each myCell In myRange.Cells 

     If myCell > 7.8 Then 
      myCell(1, 2) = "Natural" 
     Else 
      myCell(1, 2) = "Alkaline" 
     End If 

    Next myCell 

End Sub 

塊引用:了myCell(1,2)是指的當前行和E列..它會使用相對地址從當前單元格地址....因此,如果當前單元格地址是D2 ..myCell(1,2)與E2類似,myCell(1,3)表示F2,[myCell(row,column)]。