簡體   English   中英

Access 2016 VBA 按鈕在表中創建新字段

[英]Access 2016 VBA button makes new field in table

我正在嘗試在 Microsoft Access 中制作出勤跟蹤器。 有一個名為 cmdClassToRegister 的按鈕,用於在表 tblStudentData 中創建一個新字段。 但是,我無法實現這一點 - 我收到運行時錯誤 13:類型不匹配。 這是我到目前為止編寫的 VBA 代碼:

    Private Sub cmdClassToRegister_Click()
Dim CurrentDate As String
CurrentDate = Date
DoCmd.OpenTable ("tblStudentData")
Dim NewColName As String
NewColName = ("Attendance" + Str(CurrentDate))
TableDef.CreateField (NewColName)

End Sub

它應該是這樣工作的:當按鈕被點擊時,它獲取今天的日期並存儲它。 然后它打開 tblStudentData 表並嘗試寫入一個新字段。 我看不出這段代碼有什么問題,請記住,我是 Access(和 VBA)的新手。 請您幫我修復這個錯誤和我可能犯的任何其他錯誤。 謝謝 :)

此代碼將當前日期添加到“RegDate”列中。 對於日期和時間,使用“現在”而不是“日期”

Sub AddDate()
    Dim rs As Recordset
    Set rs = CurrentDb.OpenRecordset("yourTblName")
    rs.AddNew
    'RegDate must be a column in your table (e.g. string)
    rs!RegDate = Date
    rs.Update
End Sub

如果你想使用 tabledef 方法,這是正確的方法:

Private Sub cmdClassToRegister_Click()
    Dim CurrentDate As Date
    CurrentDate = Date
    Dim NewColName As String
    Dim db As Database
    Dim tdf As TableDef
    Set db = CurrentDb()
    Set tdf = db.TableDefs("tblStudentData")
    NewColName = ("Attendance" + Str(CurrentDate))
    tdf.Fields.Append tdf.CreateField (NewColName, dbText)
End Sub

您仍然需要修復代碼中的現有錯誤(str(CurrentDate) 無效,因為 str 需要一個數字而 CurrentDate 是一個日期)。 我假設你想創建一個文本字段,因此 dbText

嘗試這個:

Dim tbl As TableDef
Dim db As Database
Set tbl = db.CreateTableDef([YOURTABLE])
tbl.Fields.Append tbl.CreateField([NEW FIELD NAME], [TYPE]) 

正如 Nathan 提到的,請查看網絡上的 TableDefs(例如 MSN Dev Portal)。

而且當然:

NewColName = ("Attendance" + Str(CurrentDate))

應該:

NewColName = ("Attendance" & Str(CurrentDate))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM