从表到文本框id的自动ID

时间:2015-05-24 05:24:31

标签: ms-access

我有类似下面的代码,我希望它在表格离开时获取id到文本框id名称txtid以创建下一个新id。但它不返回我需要的值。

 Private Sub btnNew_Click()
  Call OpenControl(Me)
  Dim rs As New ADODB.Recordset
  Dim rc As New ADODB.Connection
    btnSave.Enabled = True
    Dim i As Integer
    With rs
        .CursorLocation = adUseClient
        .CursorType = adOpenDynamic
        .LockType = adLockOptimistic
        .Open "SELECT DepID FROM tbDeparture", rc

            If (.RecordCount <= 0) Then
                i = 1
            Else
                    i = .Fields(0)
                        Do Until .EOF
                            .MoveNext
                        If .EOF Then
                            i = i + 1
                            Exit Do
                        End If
                    Loop
                End If
                 txtID = i
                 .Close
    End With
    Set rs = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

如果您只需要在当前最大ID中添加一个,则可以使用此功能,但将{ID 1}设置为autonumber将是更好的选择。

Private Sub btnNew_Click()
  Call OpenControl(Me)
  Dim rs As New ADODB.Recordset
  Dim rc As New ADODB.Connection

  btnSave.Enabled = True
  Dim i As Integer
  With rs
     .CursorLocation = adUseClient
     .CursorType = adOpenDynamic
     .LockType = adLockOptimistic
     .Open "SELECT max(DepID) FROM tbDeparture", rc
         If (.RecordCount <= 0) Then
            i = 1
         Else
             i = .Fields(0) + 1
         End If
         txtID = i
        .Close
    End With
    Set rs = Nothing
End Sub