限制允许的记录数

时间:2018-03-22 09:41:55

标签: database vba ms-access max record

我有一张桌子“tbdetails”,保存学生的详细信息。简而言之,我想限制表最多只能容纳10条记录。表格“frmDetails”的表单有以下OnCurrent事件,但它不起作用:

Private Sub Form_Current()
   Forms(Detail).MaxRecords = 10
End Sub

我在线查看并发现但我可以轻松插入11条和12条记录。欢迎任何答案,VBA不是必需的(如果可以不使用它)可以通过属性菜单或其他方式完成吗?

修改

现在,当我保存时,我得到了

  

运行时错误438:对象不支持此属性或方法

所以这里肯定有问题

4 个答案:

答案 0 :(得分:2)

Private Sub Form_Current()

    Me.AllowAdditions = (Nz(DCount("[IDFieldName]","[TableName]",""),0)<10)

End Sub

基于评论似乎这已经足够了:

Me.AllowAdditions = (DCount("[IDFieldName]","[TableName]")<10)

答案 1 :(得分:2)

  

“我想将表限制为最多只能容纳10条记录”

对表格应用检查约束,使其不接受超过10行。

创建一次性程序并运行一次......

Public Sub limit_rows()
    Dim strSql As String
    strSql = "ALTER TABLE tblDetails" & vbCrLf & _
        "ADD CONSTRAINT 10_rows_max" & vbCrLf & _
        "CHECK ((SELECT Count(*) FROM tblDetails) < 11);"
    Debug.Print strSql
    CurrentProject.Connection.Execute strSql
End Sub

答案 2 :(得分:1)

如果要限制可以使用特定表单添加到表中的记录总数,可以使用以下代码:

Private Sub Form_Current()
    Dim rs As DAO.Recordset
    Set rs = Me.RecordsetClone 'Clone because we don't want to move the current record
    If Not rs.EOF Then rs.MoveLast 'Initialize recordset
    If rs.RecordCount >= 10 Then
        Me.AllowAdditions = False
    Else
        Me.AllowAdditions = True
    End If
End Sub

答案 3 :(得分:1)

需要多一点。

请参阅内联评论以了解用法:

Public Sub SetFormAllowAdditions( _
    ByVal frm As Form, _
    Optional ByVal RecordCountMax As Long = 1)

' Limit count of records in (sub)form to that of RecordCountMax.
' 2016-10-26, Cactus Data ApS, CPH
'
' Call in (sub)form:
'
'   Private Sub LimitRecords()
'       Const RecordsMax As Long = 5
'       Call SetFormAllowAdditions(Me.Form, RecordsMax)
'   End Sub
'
'   Private Sub Form_AfterDelConfirm(Status As Integer)
'       Call LimitRecords
'   End Sub
'
'   Private Sub Form_AfterInsert()
'       Call LimitRecords
'   End Sub
'
'   Private Sub Form_Current()
'       Call LimitRecords
'   End Sub
'
'   Private Sub Form_Open(Cancel As Integer)
'       Call LimitRecords
'   End Sub
'
' If the record count of a subform is to be limited, also
' the parent form must be adjusted:
'
'   Private Sub Form_Current()
'       Call SetFormAllowAdditions(Me.Form)
'   End Sub
'

    Dim AllowAdditions  As Boolean

    With frm
        AllowAdditions = (.RecordsetClone.RecordCount < RecordCountMax)
        If AllowAdditions <> .AllowAdditions Then
            .AllowAdditions = AllowAdditions
        End If
    End With

End Sub