Access VBA女士转到最后一条记录

时间:2018-04-10 08:18:28

标签: vba ms-access

我正在尝试打开表单并转到最后一条记录。 我使用以下

 DoCmd.RunCommand acCmdRecordsGoToLast

表单打开并转到最后一条记录,但它隐藏了其他记录(我必须使用滚动条)。这可能会使用户感到困惑,因为没有其他记录。

是否可以转到最后一条记录并显示最后10条记录?

1 个答案:

答案 0 :(得分:2)

这是你的幸运日 - 这是非常重要的,我已经为此目的写了一个功能。

'---------------------------------------------------------------------------------------
' Procedure : FormGotoEnd
' Author    : Andre
' Purpose   : Go to the last record of a continuous form, but don't scroll that record to the top
'             (as DoCmd.RunCommand acCmdRecordsGoToLast would do).
'             Instead scroll up so that the last record is visible at the bottom of the form.
' Parameters: F = the form, can be a subform
'             AddtlEmptyRowsBottom = if you want to have room for more than one empty row, for data entry forms
'
' Call this sub e.g. in Form_Load() or in Form_Current of the parent form, like this:
'             Call FormGotoEnd(Me)
' or          Call FormGotoEnd(Me!SubformControl.Form, 3)
'---------------------------------------------------------------------------------------
'
Public Sub FormGotoEnd(F As Form, Optional AddtlEmptyRowsBottom As Long = 0)

    Dim DetailSectionHeight As Long
    Dim nVisible As Long
    Dim nRecords As Long

On Error GoTo FormGotoEnd_Error

    ' Calculate height of full details section: Window height minus header+footer
    DetailSectionHeight = F.InsideHeight
    ' Ignore errors if form has no header or footer
On Error Resume Next
    If F.Section(acHeader).Visible Then
        DetailSectionHeight = DetailSectionHeight - F.Section(acHeader).Height
    End If
    If F.Section(acFooter).Visible Then
        DetailSectionHeight = DetailSectionHeight - F.Section(acFooter).Height
    End If
On Error GoTo FormGotoEnd_Error

    ' Number of visible records in details section
    nVisible = CLng(DetailSectionHeight / F.Section(acDetail).Height)

    ' Nothing to do if the form has no records
    If F.RecordsetClone.RecordCount > 0 Then
        ' For complex record source and/or many records, Access may not know .RecordCount yet
        ' -> calculate via .MoveLast
        F.RecordsetClone.MoveLast
        nRecords = F.RecordsetClone.RecordCount
        ' Nothing to do if all records are visible
        If nRecords > nVisible Then

            ' Move to last record. Use .Bookmark so the subform doesn't need to get focus
            F.Bookmark = F.RecordsetClone.Bookmark
            ' This is the important part!
            ' Add 2 to AddtlEmptyRowsBottom, in order to see the empty data-entry record plus one empty line
            F.SelTop = nRecords - nVisible + 2 + AddtlEmptyRowsBottom
            ' Make sure the last record is selected
            F.Bookmark = F.RecordsetClone.Bookmark

        End If
    End If

FormGotoEnd_Exit:
    On Error GoTo 0
    Exit Sub

FormGotoEnd_Error:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in FormGotoEnd", vbExclamation
    Resume FormGotoEnd_Exit

End Sub