早上看到网友提问“如何在窗体中添加自动编号字段”
其实只是简单的一条sql语句即可 "alter table " & strTblName
& " add 自动编号
autoincrement"
下面的示例是对 没有主键的 表添加自动一个自动编号的字段并设为主键。
Private Sub 表名_AfterUpdate()
Dim strKey, strsql, strTblName As String
strKey = Keyname(Me.表名.Value)
If strKey = "" Then
strTblName = Me.表名
strsql = "alter table " & strTblName & " add 自动编号 autoincrement primary key"
DoCmd.RunSQL strsql
MsgBox "添加主动编号成功"
Else
MsgBox "主键是" & strKey & "不需要添加自动编号"
End If
End Sub
'判断主键的函数。(老汉提供)
Public Function Keyname(tbname As String) As String
Dim cnn As New ADODB.Connection
Dim cat As New ADOX.Catalog
Dim tbl As ADOX.Table
Dim t As ActionEnum
Dim i As Long, j As Long
Set cnn = CurrentProject.Connection
Set cat.ActiveConnection = cnn
Set tbl = cat.Tables(tbname)
For i = 0 To tbl.Keys.Count - 1
If tbl.Keys(i).Type = 1 Then
For j = 0 To tbl.Keys(i).Columns.Count - 1
Keyname = Keyname & tbl.Keys(i).Columns(j).Name & ";"
Next
End If
Next
End Function