我有一个以下函数来返回结果数据集:
Function Dynamic_Connection_SQL(ByVal SQL As String)
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = "ODBC;Driver=SQL Server;Server=XXXX;DATABASE=XX;Trusted_Connection=Yes;"
qdf.SQL = SQL
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
rst.Close
Set rst = Nothing
Set qdf = Nothing
End Function
在ParentForm中,我有一个命令按钮,其onClick事件具有以下代码:
Private Sub Command0_Click()
Dim strSQL As String
strSQL = "SELECT ID, EmployeeID, EmployeeName " & _
"FROM XYZ " & _
"ORDER BY EmployeeName;"
Dynamic_Connection_SQL (strSQL)
Me.ChildSubForm.Form.RecordSource = Dynamic_Connection_SQL(strSQL)
End Sub
我在按钮下面有一个名为ChildForm的子窗体。
我的目标是'当用户点击命令按钮时,查询将被执行,结果数据集将显示在ChildForm'中。
我陷入困境,不知道如何继续前进。如果我执行此代码并单击按钮,则会收到错误运行时错误2467.您输入的表达式是指此行上已关闭或不存在的对象:
Me.ChildSubForm.Form.RecordSource = Dynamic_Connection_SQL(strSQL)
更新:
我已将代码更新为:
Function Dynamic_Connection_SQL(ByVal SQL As String) As DAO.Recordset
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = "ODBC;Driver=SQL Server;Server=xxxx;DATABASE=xx;Trusted_Connection=Yes;"
qdf.SQL = SQL
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
Set Dynamic_Connection_SQL = rst
End Function
并且
Private Sub Command0_Click()
Dim strSQL As String
Dim intCounter As Integer
Dim rstRet As DAO.Recordset
strSQL = "SELECT ID, ClientID, SDP_CategorySK, EmployeeID, RollupToEmployeeID, Allocation " & _
"FROM ShiftCurrentStaffing " & _
"ORDER BY EmployeeID;"
Set rstRet = Dynamic_Connection_SQL(strSQL)
With rstRet
Do While Not rstRet.EOF
Debug.Print ![ID] & " " & ![EmployeeID] & ", (" & ![EmployeeName] & ")"
MsgBox ![ID] & " "
.MoveNext
Loop
End With
Me.ChildSubForm.Form.Recordset = rstRet.OpenRecordset
Me.Requery
rstRet.Close
Set rstRet = Nothing
End Sub
消息框正确显示ID ..所以上面的代码正在运行..现在问题是我仍然收到错误运行时错误2467.您输入的表达式是指一个已关闭的对象或在这一行上不存在:
Me.ChildSubForm.Form.Recordset = rstRet.OpenRecordset
答案 0 :(得分:1)
你这样做有很大的不同,所以我可能会离开这里,但我相信问题是你的Dynamic_Connection_SQL(strSQL)
函数没有返回值,所以它不能将它分配给记录源。现在,您的函数创建记录集并填充它,然后终止并清除检索到的记录,而不将其返回到您的调用命令。