如何在Ms访问子表单中显示记录集数据

时间:2012-07-30 00:56:37

标签: ms-access-2007 recordset subform

如何在Access Sub表单控件中显示一个SQL查询的结果?我尝试了下面的代码

Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Dim qry As String

qry = "SELECT FirstName,Email FROM Customer" '
Set rs = db.OpenRecordset(qry)

Customer_enquiry_subform.Form.Recordset = rs

Customer_enquiry_subform是我的SubForm的名称。我的子表单中只有2列显示,FirstName,Email

它给我一个错误

  

运行时错误3251:操作此类型不支持   对象

有人可以告诉我我做错了吗?

2 个答案:

答案 0 :(得分:2)

我知道这个问题是2年前的问题,但对于我们这些偶然发现它并希望对Access子窗体控件使用SQL查询的人来说(许多SQL查询/存储过程太复杂而无法放入表单中)记录来源)...我发现ADO效果很好。有关详细说明,请参阅http://support.microsoft.com/kb/281998/EN-US/。为了让这个在子窗体上工作,我将代码放在子窗体上,并且打开"打开"事件 - 不是表格。

一个注意事项是子窗体不会绑定到主窗体(父/子丢失),因此您必须依赖其他代码来添加我认为的新记录。我的特定子表单是只读的,因此它不需要是父/子 - 当我调用存储过程重新创建父/子效果时,我使用主表单中的记录ID作为参数(参见下面的代码:我的例子。)

此外,如果您未指定LockType adLockPessimistic或adLockOptimisic,则此代码将无效:adLockReadOnly不起作用(请参阅In Memory, Stand-Alone, Disconnected ADO Recordset)。您将收到错误"该对象不是有效的Recordset属性"这可能会引起一点头痛。 :)

我的示例代码(我使用来自https://accessexperts.com/blog/2011/01/21/easy-adodb-recordsets-and-commands-in-access/的Juan Soto&#39的通用ADO连接示例):

   Private Sub Form_Open(Cancel As Integer)
   On Error GoTo ErrHandler
   Dim rs As ADODB.Recordset
   Dim strSQL As String
   Dim strPoint As String

   'I use my Point_ID from my main form as a parameter to fill the subform to recreate the "parent/child" effect
   strPoint = Forms!FRM_Vegetation_Strata!Point_ID
   strSQL = "sp_Report_VegWorksheet '" & strPoint & "'"

   'this method of calling the sub "OpenMyRecordset" is from Soto's example listed above
   OpenMyRecordset rs, strSQL, rrOpenStatic, rrLockOptimistic, True
   With rs
   If .RecordCount = 0 Then
   MsgBox "No records returned"
   End If
   End With

   Set Me.Recordset = rs


ExitProcedure:
    On Error Resume Next
    Exit Sub

ErrHandler:
    MsgBox Err.Description & " (" & Err.Number & ") encountered", vbOKOnly + vbCritical, "InitConnect"
    Resume ExitProcedure

    Resume
End Sub

当主窗体上的数据发生更改时刷新子窗体:

Private Sub cmdRefresh_Click()
Me.Form.Recordset.Requery
Set Me.Form.Recordset = Me.Form.Recordset
End Sub

当表单关闭时(在子表单"关闭"事件)

Private Sub Form_Unload(Cancel As Integer)
   'Close the ADO connection we opened
   On Error Resume Next
   Dim cn As ADODB.Connection
   Dim rs As ADODB.Recordset

   Set cn = Me.Recordset.ActiveConnection
   If cn.State = adStateOpen Then
    cn.Close
   End If

   Set cn = Nothing
   Set rs = Nothing
   Set Me.Recordset = Nothing

End Sub

答案 1 :(得分:1)

如果要将表单的记录源设置为记录集,则需要使用ADO。但是,我怀疑你的意思是:

 qry = "SELECT FirstName,Email FROM Customer"
 Me.Customer_enquiry_subform.Form.Recordsource = qry

换句话说,您不需要记录集,只需将记录源设置为字符串。