如何在运行中索引新的 DAO CreateField - MS Access

How to INDEX a new DAO CreateField on the Fly - MS Access

我有问题。我需要使用新创建的 table 列(字段),我刚刚将其命名为 "ID" 并对其进行索引(唯一)。我尝试了几种方法都没有成功。我所要求的只是有人提供一个全新的视角。 ~ 肖

Public Sub OrcleJEtoUnmatched()
Dim db As Database
Dim tdf As DAO.TableDef
Dim fld1 As DAO.Field, fld2 As DAO.Field
Dim idx As Index
Dim rst As DAO.Recordset
Dim hertz As String

Set db = CurrentDb()

'Copies table data from ORACLE JE Table; Creates / overwrites existing data to UNMATCHED Table (Working Table)
DoCmd.RunSQL "SELECT [Oracle JE].* INTO Unmatched FROM [Oracle JE];"

Set tdf = db.TableDefs("Unmatched")
Set fld1 = tdf.CreateField("ID", dbText, 255)
Set fld2 = tdf.CreateField("BatchCalc", dbText, 255)
With tdf
  .Fields.Append fld1
  .Fields.Append fld2
End With

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)
  rst.Edit
  rst!ID = Replace(hertz, " ", "")
  rst!BatchCalc = Mid(rst![JE Line Description], 8, 8)
  rst.Update
  rst.MoveNext
Loop
rst.Close
Application.RefreshDatabaseWindow

Set fld1 = Nothing
Set fld2 = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub

要向 DAO tabledef 对象添加索引,请使用 createindex 方法。

这是基本文档;

https://msdn.microsoft.com/EN-US/library/office/ff196791.aspx

如果您想坚持使用 DAO 对象模型来创建您的字段并为其编制索引,请查看 Access 帮助系统中的 Index.CreateField 方法

但我认为通过执行 ALTER TABLE 语句更容易做到这两点...

CurrentDb.Execute "ALTER TABLE Unmatched ADD COLUMN ID TEXT(255) UNIQUE;"

使用@HansUp 提供的答案,我对其进行了修改并使其生效。感谢@jhTyppeny 和@Hansup 的快速回复。

DoCmd.RunSQL "CREATE UNIQUE INDEX ID ON Unmatched (ID)  WITH PRIMARY"