我。在通用requery函数中失败

时间:2015-04-21 15:17:25

标签: vba ms-access access-vba

在具有多个按钮(用于添加/编辑/删除数据)的MS Access表单中,其背后有VBA代码,每个按钮子程序末尾的代码刷新屏幕,以便用户查看之前的最后一条记录单击按钮。以下是其中一个按钮的重新查询代码示例:

Dim rst As Recordset, RecordToView As String
Set rst = Me.RecordsetClone
RecordToView = CStr(ProducerID)
Me.Requery
rst.FindFirst "ProducerID = " & RecordToView
Me.Bookmark = rst.Bookmark
rst.Close

此代码或类似版本目前针对表单上的所有按钮重复。这是尝试创建一个通用函数,因此可以消除这个冗余代码:

Public Function RefreshScreen(Field As String, ByVal RecordToView As String)
    Dim rst As Recordset
    Set rst = Me.RecordsetClone
    Me.Requery
    rst.FindFirst Field & " = " & RecordToView
    Me.Bookmark = rst.Bookmark
    rst.Close
End Function

并且这样称呼:

Call RefreshScreen("ProducerID", ProducerID)

然而,当它在泛型函数中遇到Me.RecordsetClone时,它会给出“编译错误:无效使用Me关键字”消息。需要对通用函数进行哪些修改才能使其起作用?

2 个答案:

答案 0 :(得分:4)

更改过程的声明以期望引用调用表单。

Public Function RefreshScreen(ByRef frm As Form, ByVal fld As String, ByVal RecordToView As String)
    Dim rst As DAO.Recordset
    Set rst = frm.RecordsetClone
    frm.Requery
    rst.FindFirst fld & " = " & RecordToView
    frm.Bookmark = rst.Bookmark
    rst.Close
End Function

(作为旁注,因为你没有从该函数返回一个值,所以它可能是一个子程序。但这在这里无关紧要。)

然后在调用程序时包含Me

Call RefreshScreen(Me, "ProducerID", ProducerID)

我对这条评论感到惊讶,该评论指出Call()在VBA中已经过时了。我之前从未听过,但你可以在没有它的情况下调用该程序:

RefreshScreen Me, "ProducerID", ProducerID

答案 1 :(得分:0)

你或许可以这样做:

Public Function RefreshScreen( _
    ByRef FormObject As Form, _
    Byval FieldName As String, _
    ByVal RecordToView As Long)

    Dim rst As Recordset

    FormObject.Requery
    Set rst = FormObject.RecordsetClone
    If rst.RecordCount > 0 Then
        rst.FindFirst FieldName & " = " & RecordToView & ""
        If Not rst.NoMatch Then
            FormObject.Bookmark = rst.Bookmark
        End If
    End If
    rst.Close
    Set rst = Nothing

End Function

然后:

RefreshScreen Me, "ProducerID", ProducerID