访问VBA - 如何在SQL字符串中使用用户定义的函数?

时间:2014-04-05 09:13:10

标签: sql vba ms-access-2007

我正在尝试在Access 2007 VBA中创建一个参数查询,它从用户表单中获取两个输入参数,并根据我在代码中其他地方编写的公共函数RESULT返回一个派生字段值。该函数确定计算的“结果”字段的值,该字段是从基础表,[HomeTeam],[AwayTeam],[HomeGoals],[AwayGoals]中的4个字段的值派生的。

如果我通过即时窗口调试代码并将SQL字符串粘贴到Access SQL窗口,则查询运行完美,但不会从VBA运行。生成的错误是:

“运行时错误3141. SELECT语句包含拼写错误或缺失的保留字或参数名称,或者标点符号不正确。”

我不想直接在Access中运行查询,因为Parameter [season]是一个表变量。

有人知道我是否以及如何在SQL字符串中调用VBA中的用户定义函数? 我不确定这是否只是一个语法问题。

代码:

Sub sqlSeason()

Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim season As String
Dim team As String
Dim strSQL As String

Set db = CurrentDb()

DoCmd.Close acQuery, "qrySeason"

db.QueryDefs.Delete "qrySeason"

season = [Forms]![frmSeason]![comboSeason]

strSQL = "PARAMETERS [Forms]![frmClubProfile]![comboTeam] Text (255), [Forms]![frmSeason]![comboSeason] Text (255) ;" & _
"SELECT [Date], [HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals], Result([HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals]) AS Result" & _
"FROM [" & [season] & "]" & _
"GROUP BY [Date], [HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals], Result([HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals])" & _
"HAVING ((([" & [season] & "].HomeTeam) = [Forms]![frmClubProfile]![comboTeam])) Or ((([" & [season] & "].AwayTeam) = [Forms]![frmClubProfile]![comboTeam]))" & _
"ORDER BY [Date];"

Debug.Print strSQL

Set qdef = db.CreateQueryDef("qrySeason", strSQL)

DoCmd.OpenQuery "qrySeason"

End Sub

功能:

Public Function Result(ByRef HomeTeam As String, ByRef AwayTeam As String, ByRef HomeGoals As Integer, ByRef AwayGoals As Integer) As String

    team = [Forms]![frmClubProfile]![comboTeam]

    If team = HomeTeam And HomeGoals > AwayGoals Then
        result = "Home Win"
    End If
    If team = HomeTeam And HomeGoals = AwayGoals Then
        result = "Home Draw"
    End If
    If team = HomeTeam And HomeGoals < AwayGoals Then
        result = "Home Lost"
    End If
    If team = AwayTeam And HomeGoals < AwayGoals Then
        result = "Away Win"
    End If
    If team = AwayTeam And HomeGoals = AwayGoals Then
        result = "Away Draw"
    End If
    If team = AwayTeam And HomeGoals > AwayGoals Then
        result = "Away Lost"
    End If
End Function

为什么这在Access中有效但在VBA中无效?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

在评估字符串之前,尝试使用此字符串扩展字符串值:

"SELECT [Date], [HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals], Result([HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals]) AS Result" & _
"FROM [" & [season] & "]" & _
"GROUP BY [Date], [HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals], Result([HomeTeam], [AwayTeam], [HomeGoals], [AwayGoals])" & _
"HAVING ((([" & [season] & "].HomeTeam) = '" & [Forms]![frmClubProfile]![comboTeam] & "'")) Or ((([" & [season] & "].AwayTeam) = '" & [Forms]![frmClubProfile]![comboTeam] & "'))" & _
"ORDER BY [Date];"

正在扩展的价值:

[Forms]![frmClubProfile]![comboTeam]

假设comboTeam是一个字符串,如果是数字,则跳过单引号。