将表中的计算字段作为一个字符串VBA - MS Access插入

时间:2016-02-02 21:41:57

标签: sql vba ms-access dao recordset

我需要打开一张桌子(不匹配);创建一个新字段(ID);使用现有字段创建一个新的唯一字符串(赫兹);然后,最后,将这个新字符串插入表格的新字段。我被困了,因为我是新人。任何推动前进都将非常感激。

Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim Hertz As String
Dim rst As DAO.Recordset

Set db = CurrentDb()
Set tdf = db.TableDefs("Unmatched")
Set fld = tdf.CreateField("ID")
Set rst = db.OpenRecordset("Unmatched", dbOpenTable)

Do Until rst.EOF
hertz = rst![Accounting Document Item] & Mid(rst![JE Line Description], 20, 2) & Round(Abs(rst![Transaction Amount]), 0)

Debug.Print hertz 'immediate window check
---> DoCmd.RunSQL "?!?!?"
rst.MoveNext
Loop

Application.RefreshDatabaseWindow

Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub

1 个答案:

答案 0 :(得分:1)

Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim Hertz As String
Dim rst As DAO.Recordset

Set db = CurrentDb()
Set tdf = db.TableDefs("Unmatched")
Set fld = tdf.CreateField("ID", dbText, 255)
tdf.Fields.Append fld

Set rst = db.OpenRecordset("Unmatched")

Do Until rst.EOF
    Hertz = rst![Accounting Document Item] & Mid(rst![JE Line Description], 20, 2) & Round(Abs(rst![Transaction Amount]), 0)
    Debug.Print Hertz
    rst.Edit
    rst!ID = Hertz
    rst.Update
    rst.MoveNext
Loop

rst.Close
Set rst = Nothing
Set db = Nothing

This is how I would do it in code. An update query would be easier if you did not need to create the field on the fly.