访问VBA将QueryDef.SQL设置为字段名称的字符串

时间:2015-01-22 10:24:32

标签: sql vba ms-access

我试图通过创建SQL字符串然后使用dbo_lookups中的字段值来应用querydef以更改其SQL代码。 dbo_lookups表包含所有SQL字符串的列表,即strSQLByDepartment等。

当它到达行qrydef.SQL = rst!DataOut1我得到一个错误3129无效的sql语句,这是因为它试图更改querydefs sql代码说strSQLByDepartment而不是我已经声明的实际SQL代码,无论如何我可以使用我所拥有的更新到SQL代码吗?如果这有意义,请帮忙吗?

Set db = CurrentDb
Set qrydef = db.QueryDefs("Query1")
Set qrydef2 = db.QueryDefs("Query2")

strSQLByDepartment = "SELECT * " & _
"FROM Table1;"
strSQLByDepartment2 = "SELECT * " & _
"FROM Table2;"

strSQLByP = "SELECT * " & _
"FROM Table3;"
strSQLByP2 = "SELECT * " & _
"FROM Table4;"

Dim rst As DAO.Recordset
strLookups = "SELECT dbo_Lookups.Type, dbo_Lookups.DataIn, dbo_Lookups.DataOut1, dbo_Lookups.DataOut2 " & _
"FROM dbo_Lookups " & _
"WHERE (((dbo_Lookups.Type) = 'JobValueTypes')) " & _
"ORDER BY dbo_Lookups.DataIn;"

Set rst = CurrentDb.OpenRecordset(strLookups)

Do Until rst.EOF = True
    If Me.Report= rst!DataIn Then
        qrydef.SQL = rst!DataOut1
        qrydef2.SQL = rst!DataOut2
    Else
    End If
    rst.MoveNext
Loop

1 个答案:

答案 0 :(得分:0)

您需要使用Option Explicit并将字符串变量声明为类型字符串

请参阅Create Passthough Query