如何在Access VBA中以分数计算月份

时间:2019-05-29 14:54:38

标签: vba access-vba

我需要编写一个接收两个参数startdateenddate的函数,该函数返回两个日期之间的差。

说该函数为monthfractiondiff(startdate,enddate)

例如monthfractiondiff(15/01/2016,15/02/2016)将返回 ((31-15)/31)+(15/29) = 1.0333704116

monthfractiondiff(15/11/2018,15/02/2019)将返回 ((30-15)/30)+1+1+(15/28) = 3.0357142857

我徒然尝试了https://access-programmers.co.uk/forums/showthread.php?t=113589

3 个答案:

答案 0 :(得分:1)

已更新,感谢其他答案WeeBee

Function HowManyMonths(startdate As Date, Enddate As Date) As Double
Dim pctSTARTmonth As Double, pctENDmonth As Double, M As Long


'caputues percentage of month
pctSTARTmonth = Day(startdate) / Day(DateSerial(Year(startdate), Month(startdate) + 1, 1) - 1)
pctENDmonth = Day(Enddate) / Day(DateSerial(Year(Enddate), Month(Enddate) + 1, 1) - 1)


'Use Date difference function to get whole number and then combine perc
HowManyMonths = DateDiff("M", startdate, Enddate) + pctENDmonth - pctSTARTmonth


End Function

答案 1 :(得分:1)

我会选择datediff()。

datediff("d", "01/01/2019", date())/30.5

今天这让我返回了4,85245901639344。

答案 2 :(得分:1)

由于月份的天数有所不同,因此您必须按天数才能尽可能接近,因为从来没有(确切的值在一个月内或在7月/ 8月或12月/ 1月内):

' Rounds by default to two decimals, as more decimals has no meaning
' due to the varying count of days of a month.
' Optionally, don't round, by setting Round2 to False.
'
Public Function TotalMonths( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional Round2 As Boolean = True) _
    As Double

    Dim Months      As Double
    Dim Part1       As Double
    Dim Part2       As Double
    Dim Fraction    As Double
    Dim Result      As Double

    Months = DateDiff("m", Date1, Date2)
    Part1 = (Day(Date1) - 1) / DaysInMonth(Date1)
    Part2 = (Day(Date2) - 1) / DaysInMonth(Date2)

    If Round2 = True Then
        ' Round to two decimals.
        Fraction = (-Part1 + Part2) * 100
        Result = Months + Int(Fraction + 0.5) / 100
    Else
        Result = Months - Part1 + Part2
    End If

    TotalMonths = Result

End Function


' Returns the count of days of the month of Date1.
'
' 2016-02-14. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DaysInMonth( _
    ByVal Date1 As Date) _
    As Integer

    Const MaxDateValue  As Date = #12/31/9999#
    Const MaxDayValue   As Integer = 31

    Dim Days    As Integer

    If DateDiff("m", Date1, MaxDateValue) = 0 Then
        Days = MaxDayValue
    Else
        Days = Day(DateSerial(Year(Date1), Month(Date1) + 1, 0))
    End If

    DaysInMonth = Days

End Function

结果:

? TotalMonths(#2016/01/15#, #2016/02/15#)
 1.03 

? TotalMonths(#2018/11/15#, #2019/02/15#)
 3.03