创建循环以比较Excel中的两个单元格

时间:2016-02-17 16:03:26

标签: excel vba excel-vba

我写了一些代码来比较两个单元格。目前代码将D2与J2进行比较。我需要将D3与J3,D4与J4等进行比较。我知道最简单的方法是使用循环但无法使其正常工作。非常感谢任何帮助。

以下是目前的代码:

Public Sub Practice1()
    Dim UpLim As Double, LowLim As Double
    Dim outcome As String

    UpLim = Range("d2").Value
    LowLim = Range("j2").Value


    If UpLim > LowLim Then
        result = "Headroom"

    Else
        result = "NoHeadroom"
    End If

    Range("e2").Value = result

End Sub

2 个答案:

答案 0 :(得分:2)

这是一个典型的循环:

Public Sub Practice1()
    Dim UpLim As Double, LowLim As Double
    Dim outcome As String, i As Long
    For i = 2 To 10
        UpLim = Range("d" & i).Value
        LowLim = Range("j" & i).Value


        If UpLim > LowLim Then
            result = "Headroom"

        Else
            result = "NoHeadroom"
        End If

        Range("e" & i).Value = result
    Next i
End Sub

选择 i 限制以满足您的需求。

答案 1 :(得分:0)

轻微的替代方法

Public Sub Practice1()

    dim result as string
    dim x as integer
    for x = 2 to 10
      If (cells(x,4) > cells(x,10)) Then
          cells(x,5)= "Headroom"
      Else
          cells(x,5)= "NoHeadroom"
      End If
    next

End Sub