VBA计算两次在列范围内的差异

时间:2018-12-04 02:09:23

标签: excel vba excel-vba

我试图计算A5A20B5B20的每一行之间的差异,如果等于4小时,则将颜色更改为绿色。我很难设定范围。我目前一次只能做一个牢房。

Sub test()
    Dim Total As Double
    Dim Timein As Date
    Dim Timeout As Date
    Timein = CDate(Range("A7").Value)
    Timeout = CDate(Range("B7").Value)

    Total = 24 * ((Timeout - Timein))
    Debug.Print Total
    Debug.Print Format(Total, "#,##0_);(#,##0)")
    If Total = 4 Then
        Range("A7").Interior.Color = vbGreen
    End If

    Debug.Print "Number of hours = " & Total * 24
End Sub

Photo Example Here

1 个答案:

答案 0 :(得分:0)

您为什么还要为此任务使用VBA? Excel具有针对此类情况的内置命令和功能(条件格式)。使用VBA太过分了。

Sub test()

    Dim dteIn As Date
    Dim dteOut As Date
    Dim rng As Range, cll As Range

    Set rng = Range("A5:A20")

    For Each cll In rng
        dteIn = CDate(cll.Value)
        dteOut = CDate(cll.Offset(0, 1).Value)
        If CInt((dteOut - dteIn) * 24) = 4 Then
            cll.Interior.Color = vbGreen
        End If
    Next

End Sub