为了记录数据最后修改人及最后的修改日期时间,通常我们在表中需要添加修改人及修改日期字段,但如果每个表都手工去添加这2个字段,的确是一件累人的事,使用VBA代码自动为所有表添加更新人 更新日期字段(除系统表外),大家也可再扩展一下,增加录入人 录入日期时间 以及是否删除等字段,也可根据需要将录入人 修改人员等的字段类型改为长整型。
详细代码如下:
Private Sub Command0_Click()
Dim tdf As TableDef
Dim fld As DAO.Field
Dim prp As DAO.Property
Dim strFldName As String
Dim blnHavUpdateMan As Boolean
Dim blnHavUpdateDate As Boolean
On Error Resume Next
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "Msys" Then
Debug.Print tdf.Name
For Each fld In tdf.Fields
strFldName = fld.Name
'判断原来表中是否有更新人及更新日期字段
If strFldName = "FUpdateMan" Then
blnHavUpdateMan = True
End If
If strFldName = "FUpdateDate" Then
blnHavUpdateDate = True
End If
If strFldName = "FUpdateMan" Then
fld.Type = dbLong
fld.Properties("Caption") = "修改人"
fld.Properties("Description") = "修改人"
fld.DefaultValue = 0
End If
Next
'没有才添加相应的字段
If blnHavUpdateMan = False Then
Set fld = tdf.CreateField()
fld.Name = "FUpdateMan"
fld.Type = dbText
fld.Size = 25
fld.Properties("Caption") = "修改人"
fld.Properties("Description") = "修改人"
fld.DefaultValue = ""
tdf.Fields.Append fld
End If
If blnHavUpdateMan = False Then
Set fld = tdf.CreateField()
fld.Name = "FUpdatedate"
fld.Type = dbDate
fld.Properties("Caption") = "修改日期"
fld.Properties("Description") = "修改日期"
fld.DefaultValue = "date()"
tdf.Fields.Append fld
End If
End If
Next
End Sub