me.yearsback= 0.5
me.valdate = 5/31/2016
me.period = "monthly"
Thos look like UserForm Control Values, which are always Strings. The VBE Compiler is very "smart" and forgiving, but I always explicitly convert them before use.
Dim yearsback As Double
Dim valdate as Date
yearsback = CDbl(Me.yearsback
valdate = CDate(Me.ValDate)
In the interest of speed add
Dim Period as String
Period = Me.period
To make your code handle many types of periods add
Dim NumPeriods as Long 'Replaces months
NumPeriods = GetPeriods
Private Function GetPeriods(Period As String, YearsBack As Double, ValDate As Date)
If Period = "monthly" Then
GetPeriods = YearsBack * 12 + Month(ValDate)
ElseIf Period = "yearly" then
GetPeriods = YearsBack + Year(ValDate)
ElseIf Period = "quarterly" then
'Etc
End If
End Function
Private Function GetRunningDate(Period As String, ValDate As Date) As Date
If Period = "monthly" then
GetRunningDate= Format(DateAdd("m", -x + 1, Me.ValDate), "mm yyyy")
ElseIf Period = "yearly" Then
'Etc
ElseIf Period = "quarterly" Then
'etc
End If
end Function
If you repeat this style of using small easily written and proofed functions for each of the period dependent variables in the query string, your loop can handle all possible periods.
For x = 1 To Periods
runningDate = GetrunningDate(Period, ValDate)
useDateLower = runningDate
useDateUpper = GetuseDateUpper(Period, ValDate)
WP = GetWp(RunningDate)
'EP = GetEP(runningDate 'This variable is not used in your query
'UPR = GetUPR(RunningDate) 'This variable is not used in your query
qry.SQL = "SELECT IIf([tblEPdata]![IssueDate]>" & useDateLower & ",IIf([tblEPdata]![IssueDate]<" & useDateUpper & ",[tblEPdata]![GrossPremium])) AS " & WP & " FROM tblEPdata;"
Next