I tried so many times to code with my own understanding, but the VBA code did not return correct outputs as I do manually.
The objective: Return the 2 below outputs:
- a beginning date and an end date
- and a 'cost check' in text.
Specific problem
+) The beginning date must run from 01/10/2025 (my computer using dd/mm/yyyy format) to 01/11/2026 for each step of a month => 01/10/2025, 01/11/2025, 01/12/2025, ..., until 01/11/2026
+) The end date is given (01/01/2032) and can be adjusted by shifting each step quarterly for a maximum of 8 quarters (2 years) => 01/01/2032, 01/10/2031, 01/07/2031, ..., until 01/01/2030.
+) For each pair of beginning date and end date, a cost associated will be calculated and the cost check will return "Yes" if the cost <= a given threshold, or "No" if the cost > the given threshold. The cost calculation and cost check are calculated on a sheet. We only care about the "Cost check" output whether it is "Yes" or "No" based on beginning and end dates.
+) I need to start with the end date (01/01/2032) and then start checking step by step the beginning dates from 01/10/2025 to 01/11/2026. If whenever the cost check returns "Yes", stop everything and return the 2 outputs above. If for all beginning date tried, the cost check still returns "No", then I need to move backward the end date 3 months to 01/10/2031. After that, do again checking step by step the beginning dates from 01/10/2025 to 01/11/2026. If whenever the cost check returns "Yes", stop everything and return the 2 outputs above, if not, i.e. the cost check still returns "No" with the date "01/11/2026", then continue to move backward the end date.
Sub CheckdateCost()
begin_date = WorksheetFunction.Date (2025,10,1)
end_date = WorksheetFunction.Date (2032,1,1)
nb_quarters_backward_min = 0
Do While Worksheets("Sheet1").Range("Check_Cost").Value = "No" And nb_quarters_backward_min <= 8
nb_month_forward_min = 0
Do While Worksheets("Sheet1").Range("Check_Cost").Value = "No" And nb_month_forward_min <= 12
begin_date = WorksheetFunction.EDate(begin_date, nb_month_forward_min)
Worksheets("Sheet1").Range("Begin_Date_OK").Value = begin_date
nb_month_forward_min = nb_month_forward_min + 1
Loop
nb_quarters_backward_min = nb_quarters_backward_min + 1
end_date = WorksheetFunction.EDate(end_date, -3 * nb_quarters_backward_min)
Worksheets("Sheet1").Range("End_Date_OK").Value = end_date
Loop
Worksheets("Sheet1").Range("Begin_Date_OK").Value = begin_date
Worksheets("Sheet1").Range("End_Date_OK").Value = end_date
End Sub
Datefunction in the WorksheetFunction object. 2. Not reset the innerWhilevariablenb_month_forward_min. 3. Stepping should be constant1and-3for respectiveEdatefunctions.