我试图更改子窗体的记录集以显示查询结果
所以我有一个字符串查询:
sQueryCurrencyRate = "SELECT * FROM Table.Mytable WHERE As_Of_Date =" & Format(dateField.value, "M/d/yyyy")
sQueryCurrencyUsDollar = "SELECT * FROM Table.Mytable WHERE As_Of_Date =" & Format(dateField.value, "M/d/yyyy")
因此,当我写这篇文章时,子表格会显示一个没有错误的结果:
Me.subformName.Form.RecordsourceSourceObject = "Table.tableName"
但是当我尝试以下所有内容时,我总会收到错误:
Forms!formName.subformName.Form.RecordSource= sQueryCurrencyRate
我也尝试过:
Me.subFormName.Form.RecordsourceSourceObject= sQueryCurrencyRate
另外,
Me.subFormName.RecordsourceSourceObject= sQueryCurrencyRate
无论我做什么,我总是会收到此错误消息:
您输入的表达式是指关闭的对象或 不存在
我做错了什么?以及如何在子表单记录源中正确显示查询结果?
P.S:sql查询语法很好,因为我之前用以下方法对它们进行了测试:
Set db = CurrentDb
Set rs = db.OpenRecordset(sQueryCurrencyRate)
我没有收到错误,所以问题是如何将子表单结果绑定到查询
编辑:
我调用代码的方式如下:
Function detectSelectedQuery(sTypeDonnee As String)
sQueryCurrencyRate = "SELECT * FROM Table.Mytable WHERE As_Of_Date = ' " & Format(dateField.value, "M/d/yyyy") &"'"
Me![Child8].Form.RecordSource = sQueryCurrencyRate
end function
然后当组合框改变时,我调用函数:
Private Sub Combo_descriptionQueries_Change()
detectSelectedQuery (Combo_descriptionQueries.Value)
End Sub
答案 0 :(得分:2)
如果要正确执行此操作(没有任何SQL注入风险),可以使用ADODB记录集:
Dim cmd As New ADODB.Command
cmd.CommandText = "SELECT * FROM Mytable WHERE As_Of_Date = @MyDate"
cmd.ActiveConnection = CurrentProject.Connection
cmd.ActiveConnection.CursorLocation = adUseClient
cmd.Parameters("@MyDate") = cmd.CreateParameter("MyDate", adDate)
cmd.Parameters("@MyDate").Value = datefield.Value
Set Me.Recordset = cmd.Execute
请注意,这需要引用ActiveX数据对象库
答案 1 :(得分:1)
使用此:
sQueryCurrencyRate = "SELECT * FROM Mytable WHERE As_Of_Date = #" & Format(dateField.value, "yyyy\/mm\/dd") & "#"
为避免连接,您可以使用TempVars或创建一个小辅助函数:
' Public variable:
Dim FilterDate As Date
Public Function GetFilterDate() As Date
GetFilterDate = FilterDate
End Function
然后增加一行代码:
FilterDate = Me!dateField.Value
sQueryCurrencyRate = "SELECT * FROM Mytable WHERE As_Of_Date = GetFilterDate()"
答案 2 :(得分:1)
由于这是在Access中,为什么不使用带参数查询的默认DAO接口而不是ADODB?不需要ActiveX数据对象引用。
Dim qdf As DAO.QueryDef
'For an existing query
Set qdf = CurrentDb().QueryDefs("qryName")
'To create query (Credit to @Erik von Asmuth for pointing this out)
Set qdf = CurrentDb().CreateQueryDef("", "PARAMETERS [@MyDate] DateTime; SELECT * FROM Mytable WHERE As_Of_Date = [@MyDate];")
qdf.Parameters("[@MyDate]").Value = Date()
Set Me.Recordset = qdf.OpenRecordset()