You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MS Project 2024中Application.DateDifference返回0结果问题求助

MS Project v2409中Application.DateDifference返回0引发除零错误(v2108正常)

问题详情

  • 版本差异:在Project v2108机器上运行VBA代码时,Application.DateDifference计算日期差正常;但在v2409机器上,该函数始终返回0,直接导致percent_complete = spent_time / total_time触发除零溢出错误。
  • 无其他提示:未收到权限、宏禁用等报错信息,定位问题耗时较长。
  • 选型原因:必须基于项目日历计算时间差,DateDiff不支持此逻辑(但DateDiff在v2409上运行正常)。

代码示例(伪代码整理)

Sub progresscalculation
    ' 询问用户预测日期、校验输入、用CDate转换为日期类型
    ' 遍历项目任务,针对非摘要任务执行计算
    nonsummary_task.Number16 = percent_forecast(start_date, end_date, forecast_date)
    ' 后续逻辑
End Sub

Function percent_forecast(start_date As Variant, end_date As Variant, forecast_date As Variant)
    ' 基础场景校验(如100%完成、0%完成等)
    If Not basic_scenario Then
            total_time = (Application.DateDifference(start_date, end_date) / (ActiveProject.HoursPerDay * 60))
            spent_time = Application.DateDifference(start_date, Int(forecast_date) + ActiveProject.DefaultFinishTime) _
                / (ActiveProject.HoursPerDay * 60)
            percent_complete = spent_time / total_time
    End If
    percent_forecast = percent_complete
End Function

排查与解决方法

1. 显式指定日历参数

Project v2409可能修改了Application.DateDifference的默认行为,需要显式传入日历对象才能正确计算:

' 使用任务关联的日历
total_time = (Application.DateDifference(start_date, end_date, nonsummary_task.Calendar) / (ActiveProject.HoursPerDay * 60))
spent_time = Application.DateDifference(start_date, Int(forecast_date) + ActiveProject.DefaultFinishTime, nonsummary_task.Calendar) _
    / (ActiveProject.HoursPerDay * 60)

' 若任务无自定义日历,改用项目基准日历
' total_time = (Application.DateDifference(start_date, end_date, ActiveProject.Calendar) / (ActiveProject.HoursPerDay * 60))

2. 校验日期参数有效性

确保传入的日期是符合Project规则的有效日期,避免隐式类型转换导致的异常:

Function percent_forecast(start_date As Variant, end_date As Variant, forecast_date As Variant)
    ' 先校验日期有效性
    If Not IsDate(start_date) Or Not IsDate(end_date) Or Not IsDate(forecast_date) Then
        percent_forecast = 0
        Exit Function
    End If
    ' 校验预测日期是否在任务时间范围内
    If forecast_date < start_date Or forecast_date > end_date Then
        percent_forecast = IIf(forecast_date < start_date, 0, 100)
        Exit Function
    End If
    ' 原有逻辑...
End Function

3. 替代方案:利用任务内置属性计算

若Application.DateDifference的兼容性问题无法解决,可直接调用任务的内置属性获取基于日历的时间差:

' 总工期(自动适配项目日历,单位为分钟)
total_time = nonsummary_task.Duration / 1
' 从任务开始到预测日期的已消耗时间
spent_time = Application.DateDifference(nonsummary_task.Start, forecast_date, nonsummary_task.Calendar) / 1

4. 打印日志排查差异

在代码中添加调试日志,对比两台机器的日期参数、日历配置差异:

Debug.Print "Start: " & start_date, "End: " & end_date, "Forecast: " & forecast_date
Debug.Print "Project Hours/Day: " & ActiveProject.HoursPerDay
Debug.Print "Task Calendar: " & nonsummary_task.Calendar.Name

内容的提问来源于stack exchange,提问作者Stgauss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 03:46:01