Agnes
Agnes

Reputation: 86

calculate with month, part of months

What I need is to calculate the availability (WTF) in a month and divide them by the days of the month from a selected period of months.

The formula should be: WTF/total days a month * available days of month = result

for example:

period: 07-09-2017 - 15-11-2017
WTF: 0.5

Should result in:

September: 0,4000
October:   0,5000
November:  0,2500

My question is how to calculate the result when there are more then 2 months in the period. I cannot figure out how to calculate the results of the months between the first and last month, so in this case of the month October.

Upvotes: 1

Views: 56

Answers (1)

CallumDA
CallumDA

Reputation: 12113

Here's some code to get you started. It outputs the values in one string, but you can easily have it output to three different cells:

Public Function OutputWork(first As Date, last As Date, wtf As Double)
    Dim worked As Object, total As Object
    Dim i As Date
    Dim j As Long
    Dim mnth As String, key As String
    Dim v As Variant

    Set worked = CreateObject("Scripting.Dictionary")
    Set total = CreateObject("Scripting.Dictionary")

    For i = WorksheetFunction.EoMonth(first, -1) + 1 To WorksheetFunction.EoMonth(last, 0)
        mnth = Format(i, "mmmm")
        If Not total.exists(mnth) Then
            total.Add key:=mnth, Item:=1
        Else: total.Item(mnth) = total.Item(mnth) + 1
        End If

        If Not worked.exists(mnth) Then worked.Add key:=mnth, Item:=0
        If i >= first And i <= last Then worked.Item(mnth) = worked.Item(mnth) + 1
    Next i

    ReDim v(LBound(total.keys()) To UBound(total.keys()))
    For j = LBound(v) To UBound(v)
        key = total.keys()(j)
        v(j) = key & ":" & wtf / total.Item(key) * worked.Item(key)
    Next j

    OutputWork = Join(v, ", ")
End Function

Use the function on the worksheet like this:

=OutputWork(<start>,<end>,<WTF>)

enter image description here

Upvotes: 4

Related Questions