3

I have a piece of code that takes the value in a cell and sets a different cell based on the value. It is a simple code, I just can not figure out how to loop it to go through the whole column. Can some one guide me to how this can be done? Thanks in advance!

Here is the code I have:

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
4

3 回答 3

6

你还不需要 VBA

在 E2 中设置公式'= IIF(D2<=7.8;"Neutral";"Alkaline")'

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

于 2013-06-03T15:17:47.953 回答
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
于 2013-06-03T15:25:09.387 回答
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 )]。

于 2013-06-04T08:03:05.063 回答