访问VBA - 使用书签删除过滤器并保持当前记录

问题描述 投票:1回答:2

在Access 2010中,我有一个表单,可以使用过滤器打开特定记录或记录:

DoCmd.OpenForm "frmStories", , , "StoryID = " & someNumber

使用下面的代码(source)让我删除过滤器并保留在当前记录...或者我认为。表单的一部分 - 即由VBA计算的字段 - 仍然认为它们在第一条记录上,使用StoryID = 1,因此显示错误的结果。

Dim varFilterID As Variant

Public Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)

    'Note current record if filter is removed
    If ApplyType = acShowAllRecords Then
        varFilterID = Me.StoryID
        Debug.Print "ApplyFilter"
    End If

End Sub

Private Sub Form_Current()        
    ' If the filter is OFF, and we have a stored ID from the filter setting,
    ' use standard bookmark code to return to the record selected for the filter.

    If Me.FilterOn = False Then
        If Nz(varFilterID) <> "" Then
            Dim rs As DAO.Recordset
            Dim strCriteria As String
            Set rs = Me.RecordsetClone
            strCriteria = "StoryID = " & varFilterID
            Debug.Print "varFilterID=" & varFilterID & " storyID = " & Me.StoryID & " 1st"
            If rs.NoMatch = False Then Me.Bookmark = rs.Bookmark
            ' Reset the stored filterID so that the code does not keep forcing this
            ' selection as the user navigates through the records.
            varFilterID = Null
            Set rs = Nothing
            Debug.Print "varFilterID=" & varFilterID & " storyID = " & Me.StoryID & " 2nd"

        End If
    End If

    'other stuff    
End Sub

单步执行代码显示它第一次运行正常,到达子结束然后再次触发Form_Current(为什么?),此时Me.StoryID恢复为1.这让我觉得问题有点问题使用事件触发顺序(ApplyFilter似乎在'当前完成后'触发''。

分页到之前的记录并重新修复它;并且当放置在命令按钮中时,代码完美地工作。

我究竟做错了什么?或者,我可以采取另一种方法吗? (我需要过滤几个非连续的记录,因此不能选择使用.FindFirst加载表单。)

ETA:我添加了一些Print.Debug行来查看发生了什么。这是结果:

ApplyType
varFilterID=35 storyID = 1 1st
varFilterID=35 storyID = 35 1st
varFilterID= storyID = 35 2nd
varFilterID= storyID = 1 2nd      <- resets between Current's End Sub and the last Current
vba access-vba ms-access-2010 recordset
2个回答
0
投票

在应用oder删除过滤器后,我会尝试Me.Refresh。


0
投票

问题如下:If rs.NoMatch = False Then Me.Bookmark = rs.Bookmark在表单中移动当前记录,触发另一个Form_Current,可能触发无限循环。

您可以尝试将Form_Current的速率限制为仅每秒触发一次:

Private lastCurrent As Date
Private Sub Form_Current()
   If lastCurrent < Now() - #00:00:01# Then Exit Sub
   LastCurrent = Now()

请注意,根据代码运行的时间长短,您可能需要增加秒数。

但请注意,这很可能是一个XY问题。您可以在打开表单时移动到特定记录,而无需按以下方式应用过滤器

Dim frm As Form
Application.ScreenUpdating = False
DoCmd.OpenForm "frmStories"
Set frm = Forms!frmStories
Dim rs As RecordSet
Set rs = frm.RecordsetClone
strCriteria = "StoryID = " & someNumber
rs.FindFirst strCriteria
If rs.NoMatch = False Then frm.Bookmark = rs.Bookmark
Application.ScreenUpdating = True

实现这一目标的其他技术可能是使用OpenArgs,这是我经常使用的。

© www.soinside.com 2019 - 2024. All rights reserved.