VBA 计算两个日期差,DateDiff 一个函数就够
VBA 里算两个日期差,DateDiff 是最常用的办法。直接看代码。
Function CalculateDateDifference(startDate As Date, endDate As Date) As Long
' 使用DateDiff函数计算两个日期之间的天数差
CalculateDateDifference = DateDiff("d", startDate, endDate)
End Function
Sub TestCalculateDateDifference()
Dim startDate As Date
Dim endDate As Date
Dim difference As Long
' 设置起始日期和结束日期
startDate = #2025/04/01#
endDate = #2025/04/10#
' 调用函数计算日期差
difference = CalculateDateDifference(startDate, endDate)
' 输出结果
MsgBox "The difference between the dates is: " & difference & " days"
End Sub
函数本身没几行,就是包了一层 DateDiff。参数 startDate 和 endDate 都是 Date 类型,返回 Long。DateDiff 的第一个参数 "d" 表示按天算,所以返回的是天数差。
测试子程序里设了两个日期,2025/04/01 和 2025/04/10,调一下函数,结果用 MsgBox 弹出来。这里日期字面量要写成 #2025/04/01# 这种格式,VBA 才认得。
用这种方式,任意两个日期之间的天数差都能算出来。DateDiff 也支持月、年这些单位,只是这里场景是天数,所以固定写 "d" 就行。
lcjmSSL简化SSL证书申请流程,对接Let's Encrypt、Google和Zerossl等主流ACME渠道,保障证书的权威性和兼容性。支持自动域名验证,提供HTTP代理、DNS代理等多种验证方案,无需手动操作,大幅节省用户时间,同时支持自动部署,证书签发后可自动同步至服务器。

浙公网安备 33010602011771号