【问题标题】:Excel VBA Comparing between a given date and (given date - 2 months)Excel VBA比较给定日期和(给定日期 - 2个月)
【发布时间】:2015-12-23 09:45:53
【问题描述】:

我正在编写代码以确保系统的数据日期不迟于 2 个业务月末日期。例如,如果系统的作业运行日期为 23/12/2015,则有效数据日期为 30/10/2015 和 30/11/2015。所涉及的日期仅为工作日。

我有以下代码:

If DateDiff("m", dataDate, jobRunDate) > 2 Then
    MsgBox "Error in dataDate"
End If

但是,我不知道如何找到:

  1. 当月的最后一天
  2. 计算 2 个工作日后

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 什么是“营业月”?
  • 一个月的工作日,基本上是周一到周五..

标签: vba excel date


【解决方案1】:

要找到一个月的最后一天,可以找到下个月的第一天并减去一天:

Dim last As Date
Dim current As Date

current = Now
last = DateSerial(Year(current), Month(current), 1) - 1
Debug.Print last

要获得一个月的最后一个工作日,只需减去天数,直到它是工作日:

Do While Weekday(last, vbMonday) > 5
    last = last - 1
Loop
Debug.Print last

结合这两个想法并将其提取为一个函数可以得到:

Private Sub Example()

    Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 1)
    Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 2)

End Sub

Private Function LastBizDayOfMonth(inYear As Integer, inMonth As Integer) As Date
    LastBizDayOfMonth = DateSerial(inYear, inMonth + 1, 1) - 1
    Do While Weekday(LastBizDayOfMonth, vbMonday) > 5
        LastBizDayOfMonth = LastBizDayOfMonth - 1
    Loop
End Function

【讨论】:

    【解决方案2】:

    以下是获取一个月最后一天的方法:

    Sub LastDayOfMonth()
        Dim d As Date
        mnth = 12
        yr = 2015
        d = DateSerial(yr, mnth + 1, 0)
        MsgBox d
    End Sub
    

    然后您必须从该日期减去两个月。如果结果是在周六或周日,您必须决定是前进到下周一还是后退到上周五。

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2014-02-05
      • 2018-02-17
      相关资源
      最近更新 更多