VBA - 计算列中两个日期值之间的天数差异

时间:2016-03-18 03:01:30

标签: vba excel-vba excel

我想创建一个脚本,我可以计算两个日期值Column AColumn B之间的天数差异,如果Day Value大于15,则将其标记为{{1} }。如果没有采取行动......

示例:

"15 days!"

输出:

Column A0 | Column B   | Column C |
01/2/2016 | 01/17/2016 |          |
01/3/2016 | 01/05/2016 |          |
01/4/2016 | 01/20/2016 |          |

我的代码:

 Column A0 | Column B   | Column C |
 01/2/2016 | 01/17/2016 | 15 days! |
 01/3/2016 | 01/05/2016 |          |
 01/4/2016 | 01/20/2016 | 15 days! |

我理解我需要使用DateDiff函数来计算天数,但我仍然对如何使用Dim firstDate As Date, secondDate As Date Dim result As Integer Set Sheet2 = Workbooks.Open(TextBox2.Text).Sheets(1) firstDate = Sheet2.Range("A" & Rows.Count).End(xlUp).Row secondDate = Sheet2.Range("B" & Rows.Count).End(xlUp).Row If result = DateDiff("d", firstDate, secondDate) > 15 Then Sheet2.Cells(result, 3) = 15 days! End If column A的值进行混淆并将其用作column Bfirstdate值。有人可以帮我这个吗?!

1 个答案:

答案 0 :(得分:3)

试试这个。

Sub CalculateDate()
Dim Result, RowNo As Long
Dim FirstDate, SecondDate As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets(1)

RowNo = 1

    Do Until ws.Cells(RowNo, 1) = ""

    FirstDate = ws.Cells(RowNo, 1)
    SecondDate = ws.Cells(RowNo, 2)

        If DateDiff("d", FirstDate, SecondDate) >= 15 Then
        ws.Cells(RowNo, 3) = "15 DAYS!"
        End If

    RowNo = RowNo + 1

    Loop

End Sub