VBA循环遍历列中的值并根据值更改下一列

时间:2013-06-03 15:13:05

标签: excel vba excel-vba excel-2010

我有一段代码可以获取单元格中的值,并根据值设置不同的单元格。这是一个简单的代码,我只是无法弄清楚如何循环它来完成整个列。有人可以指导我如何做到这一点?提前谢谢!

这是我的代码:

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 个答案:

答案 0 :(得分:6)

您还不需要VBA

在您的E2 '= IIF(D2<=7.8;"Neutral";"Alkaline")'

中设置公式

您可以将其复制到E列以下

答案 1 :(得分:3)

如果要在VBA中执行此操作,可以创建“直到”循环,直到列中没有更多值:

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

答案 2 :(得分: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
  

Blockquote: myCell(1,2)引用当前行和E列..它将使用当前单元格地址的相对地址....所以如果当前单元格地址是D2 ..myCell(1,2)与E2同等有意义myCell(1,3)表示F2,[myCell(row,column)]。