Access 2007 VBA:如何获取/更改当前记录在屏幕上的位置

时间:2012-10-25 20:13:22

标签: vba ms-access ms-access-2007

我有一个显示40行的Access 2007表单。当我打开它时,我希望当前记录的行显示在显示的40行中的行位置#5。换句话说,当前行上方应有4行,下方有35行。

MoveUpDown 是我第一次执行此操作,但目前仅在当前记录的行(由 FindFirst 移动)最初显示在行位置时才有效# 1到#5。如何找到当前行的显示位置,相对于显示的行,以及如何更改它?感谢。

Private Sub OpenMyFormTo(sqlWhere As String)
    Dim rs As DAO.Recordset, frm As Form
    DoCmd.Openform "myForm", acNormal
    Set frm = Forms("myForm").Form
    Set rs = frm.RecordsetClone
    If Not (rs.BOF And rs.EOF) Then
        rs.MoveFirst
        rs.FindFirst sqlWhere
        frm.Bookmark = rs.Bookmark
        MoveUpDown frm.Recordset, 5
    End If
End Sub

Private Sub MoveUpDown(rs As DAO.Recordset, RowsToMove As Integer)
    Dim RowsActuallyMoved As Integer, i As Integer
    RowsActuallyMoved = 0
    For i = 1 To RowsToMove
        If Not rs.BOF Then
            rs.MovePrevious
            RowsActuallyMoved = RowsActuallyMoved + 1
        End If
    Next i
    For i = 1 To RowsActuallyMoved
        If Not rs.EOF Then rs.MoveNext
    Next i
End Sub

2 个答案:

答案 0 :(得分:1)

我不完全确定这是否是你所需要的:
a)直接进入第5条记录,使用: DoCmd.GoToRecord acDataForm, Me.Name, acGoTo, 5
(Me.Name仅在代码位于表单自己的代码模块中时) b)您可以使用查询当前位置 Me.Recordset.AbsolutePosition
奇怪的是,.AbsolutePosition开始计数为0,goto-command为1。

答案 1 :(得分:1)

我相信我有一个答案,虽然对我来说似乎很笨拙。此过程找到目标行,向下滚动直到目标行不可见,向上滚动到目标行,通过(偏移)其他行超过目标,然后向下滚动到目标行。结果是目标行显示为(偏移+ 1)可见行。如果行数<偏移,然后显示为最后一行。

Private Sub DisplayWithOffset(frm As Form, sqlWhere as String, Offset As Integer)

    Dim rs As DAO.Recordset, DetailsHt As Long, RowHt As Long, i As Integer
    Dim RowsVisible As Integer, BookmarkAP As Integer, RowsMoved As Integer

    DetailsHt = frm.InsideHeight _
              - frm.Section(acHeader).Height - frm.Section(acFooter).Height
    RowHt = frm.Section(acDetail).Height
    RowsVisible = IIf(RowHt > 0, DetailsHt Mod RowHt, 0)
    Set rs = frm.Recordset

    If Not (rs.BOF And rs.EOF) Then

        rs.MoveLast
        rs.FindFirst sqlWhere

        BookmarkAP = rs.AbsolutePosition

        RowsMoved = 0
        For i = 1 To RowsVisible
            If rs.AbsolutePosition + 1 < rs.RecordCount Then
                rs.MoveNext
                RowsMoved = RowsMoved + 1
            End If
        Next i

        Do Until rs.AbsolutePosition = BookmarkAP
            rs.MovePrevious
        Loop

        RowsMoved = 0
        For i = 1 To Offset
            If rs.AbsolutePosition > 0 Then
                rs.MovePrevious
                RowsMoved = RowsMoved + 1
            End If
        Next i

        For i = 1 To RowsMoved
            rs.MoveNext
        Next i

    End If

End Sub