CSharp821
CSharp821

Reputation: 360

First Day Of Month For Calculated Number Of Months

I'm running into an issue where I need some more guidance. I've got a form that allows users to enter a start date and end date to represent the length of a contract. I'm using the following query to calculate the monthly amount :

SELECT t_Actuals.InvoiceAmount,
 (DateDiff("m",[StartDate],[EndDate])+1) AS [Contract Term],
 CCur(Round(([InvoiceAmount]/[Contract Term]),0)) AS MonthlyAmount
 FROM t_Actuals;

Our VP wants the MonthlyAmount projected throughout the length of the Contract Term (ie. 11 months from Start Date). Ideally, I would like to allocate the MonthlyAmount in a MM-YYYY (01/2012, 02,2012) format throughout the length of the contract term, but, admittedly, I am not that experienced with working with dates in Access outside of the Query Grid.

Regardless, I've been reading about the DateSerial function to find the first day of the month, but how would you implement that into a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount.

Sorry, this is kind of a convuluted question. Any advice would be greatly appreciated. Thank you in advance for any direction.

Upvotes: 1

Views: 345

Answers (1)

HansUp
HansUp

Reputation: 97131

"a loop to find the value of the first date of the month for the next 36 months and write that date to a table with the projected date as fldDate and MonthlyAmount"

Given the starting date of the first month and the number of months, you can use the DateAdd() function to determine the rest of the dates you need to insert. Open your table as a DAO recordset, use its .AddNew method to add a row, assign the values you want in the fields, and call .Update to store the row.

Sounded like your challenge was for the date piece, so I sketched that out and left the MonthlyAmount piece for you to complete.

Public Sub LoadMonthStartDates(ByVal pFirstDate As Date, _
        ByVal pMonths As Long)
    Const cstrTable = "YourTableNameHere"
    Dim db As DAO.database
    Dim rs As DAO.Recordset
    Dim i As Long

    Set db = CurrentDb
    Set rs = db.OpenRecordset(cstrTable, dbOpenTable, dbAppendOnly)
    For i = 1 To pMonths
        rs.AddNew
        rs!fldDate = DateAdd("m", i - 1, pFirstDate)
        'rs!MonthlyAmount = <your calculated amount>
        rs.Update
    Next
    rs.Close
    Set rs = Nothing
    Set db = Nothing
End Sub

Upvotes: 1

Related Questions