【问题标题】:vba access query with variables带有变量的vba访问查询
【发布时间】:2016-05-16 19:22:06
【问题描述】:

我收到运行时错误 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

【问题讨论】:

    标签: vba ms-access


    【解决方案1】:

    通过查看您的查询,我认为Dates 的格式应该在''yyyymmddyyyy-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]"
    

    【讨论】:

    • 所以在修正了语法之后,代码仍然没有按照我的意愿去做。我创建的查询中只显示一列(最后一列),而不是每个月都有一列。我该怎么做?
    • @zkhan 我意识到您缺少 FALSE 值SELECT IIF([Condition], TRUE = IIF([Condition], TRUE= [GrossPremium] , Missing False), Missing False)
    【解决方案2】:

    我首先要改变的是这一行:

    qry.SQL = _
    "SELECT IIf([IssueDate] > #" & useDateLower & "#," & _
    "IIf([IssueDate] < #" & useDateUpper & "#," & _
    "[GrossPremium])) AS [" & WPmonthly & "] FROM tblEPdata;"
    

    还需要 WPmonthly 周围的括号。我也会尝试使用刘海而不是句号(Me!Period)来改变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多