我收到运行时错误3141,其中说明SELECT语句包含拼写错误或缺失的保留字或参数名称,或者标点符号不正确。在用户表单单击时,我正在尝试使用循环,其中使用变量输入定义查询中的多个字段。我在哪里错了?
Private Sub Calculate_Click()
Dim db As Database
Dim x As Integer
Dim y As Integer
Dim WPmonthly As String ' field name for monthly written premium
Dim UPRmonthly As String ' field name for monthly unearned premium
Dim EPmonthly As String ' field name for monthly earned premium
Dim runningDate As Date
Dim useDateLower As Date
Dim useDateUpper As Date
Dim qry As dao.QueryDef
Months = Me.YearsBack * 12 + Month(Me.ValDate)
If Me.Period = "monthly" Then
Set db = CurrentDb
Set qry = CurrentDb.CreateQueryDef("MyQuery")
Debug.Print qry.SQL ' shows the SQL from MyQuery
For x = 1 To Months
runningDate = Format(DateAdd("m", -x + 1, Me.ValDate), "mm yyyy")
useDateLower = runningDate
useDateUpper = Format(DateAdd("m", -x + 2, Me.ValDate), "mm yyyy")
WPmonthly = "WP M" & Month(runningDate) & " " & Year(runningDate)
EPmonthly = "EP M" & Month(runningDate) & " " & Year(runningDate)
UPRmonthly = "UPR M" & Month(runningDate) & " " & Year(runningDate)
qry.SQL = "SELECT IIf([tblEPdata]![IssueDate]>" & useDateLower & ",IIf([tblEPdata]![IssueDate]<" & useDateUpper & ",[tblEPdata]![GrossPremium])) AS " & WPmonthly & " FROM tblEPdata;"
Next
qry.Close
End If
end sub
答案 0 :(得分:0)
我要改变的第一件事是这一行:
qry.SQL = _
"SELECT IIf([IssueDate] > #" & useDateLower & "#," & _
"IIf([IssueDate] < #" & useDateUpper & "#," & _
"[GrossPremium])) AS [" & WPmonthly & "] FROM tblEPdata;"
还需要在WPmonthly附近使用括号。我也会尝试使用刘海代替句点(Me!Period)。
答案 1 :(得分:0)
通过查看您的查询我认为Dates
的格式应该是''
和yyyymmdd
或yyyy-mm-dd
格式之间的格式以及最后;
格式查询语句。
你有类似的东西:
useDateLower = 01/05/2016
Excel
了解它,但SQL不理解,因此,您必须将日期与''
或##
相关联,并且您的查询结束如下:
... [tblEPdata]![IssueDate]> '' " & useDateLower & " '' ,IIf([tb...
您可以在表格中添加别名。
qry.SQL = "SELECT IIf([TBL].[IssueDate]> ''" & useDateLower & _
"'',IIf([TBL].[IssueDate]< ''" & useDateUpper & _
"'',[TBL].[GrossPremium])) AS " & WPmonthly & _
" FROM tblEPdata AS [TBL]"