在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
单步执行代码显示它第一次运行正常,到达sub的末尾然后再次触发Form_Current(为什么?),此时Me.StoryID恢复为1这让我觉得这个问题与事件触发顺序有关(ApplyFilter似乎触发&#39;&#39;&#39;&#39;当前已完成)。< / p>
分页到上一条记录并重新修复它;当放置在命令按钮中时,代码可以正常工作。
我做错了什么?或者,我可以采取另一种方法吗? (我需要过滤几个非连续的记录,因此不能选择使用.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
答案 0 :(得分:0)
我会在应用oder删除过滤器后尝试使用Me.Refresh。
答案 1 :(得分: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
,这是我经常使用的。