我得到運行時錯誤3141,它表示SELECT語句包含保留字或參數名拼寫錯誤或缺失,或標點符號不正確。在用戶表單上單擊,我試圖使用循環,查詢中的多個字段使用變量輸入定義。我在哪裏錯了?帶變量的vba訪問查詢
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
所以在修復語法後,代碼仍然沒有做到我想要的。在我創建的查詢中只顯示一列(最後創建的一列),而不是每個月都有一列。我會怎麼做? – zkhan
@zkhan我意識到你缺少FALSE值'SELECT IIF([Condition],TRUE = IIF([Condition],TRUE = [GrossPremium],Missing False),Missing False) –