Access 2010 - 运行时错误3022

时间:2017-01-08 14:14:02

标签: ms-access-2013

我正在尝试将记录添加到名为“Topics”的现有表中(以下代码中的“For EachToticsCtl.ItemsSelected中的每个SelectedTopic”部分)。 执行代码时,我总是得到“运行时错误'3022':您对表请求的更改不成功,因为它们会在索引,主键或关系中创建重复值。所以在创建时会出错字段“ID”中的自动编号(=唯一被索引的字段 - 没有重复)。 调试时,会突出显示以下代码中的“TopicRecord.Update”行。 我在这个论坛和其他论坛上已经阅读了几个关于这个主题的帖子,但仍然无法让这个工作 - 我必须忽视一些事情....

Private Sub Copy_Click()

Dim JournalEntrySourceRecord, JournalEntryDestinationRecord, TopicRecord As Recordset
Dim JournalEntryToCopyFromCtl, JournalEntryToCopyToCtl, JournalEntryDateCreatedCtl, SelectedTopicsCtl As Control
Dim Counter, intI As Integer
Dim SelectedTopic, varItm As Variant

Set JournalEntryToCopyFromCtl = Forms![Copy Journal Entry]!JournalEntryToCopyFrom
Set JournalEntryToCopyToCtl = Forms![Copy Journal Entry]!JournalEntryToCopyTo
Set JournalEntryDateCreatedCtl = Forms![Copy Journal Entry]!JournalEntryDateCreated
Set JournalEntrySourceRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyFromCtl.Value)
Set JournalEntryDestinationRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyToCtl.Value)
Set SelectedTopicsCtl = Forms![Copy Journal Entry]!TopicsToCopy
Set TopicRecord = CurrentDb.OpenRecordset("Topics", dbOpenDynaset, dbSeeChanges)


With JournalEntryDestinationRecord
    .Edit
    .Fields("InitiativeID") = JournalEntrySourceRecord.Fields("InitiativeID")
    .Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
    .Fields("Comment") = JournalEntrySourceRecord.Fields("Comment")
    .Fields("Active") = "True"
    .Fields("InternalOnly") = JournalEntrySourceRecord.Fields("InternalOnly")
    .Fields("Confidential") = JournalEntrySourceRecord.Fields("Confidential")
    .Update
    .Close
End With
JournalEntrySourceRecord.Close
Set JournalEntrySourceRecord = Nothing
Set JournalEntryDestinationRecord = Nothing

For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected
    TopicRecord.AddNew
    For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
        TopicRecord.Fields(Counter) = SelectedTopicsCtl.Column(Counter, SelectedTopic)
    Next Counter
    TopicRecord.Fields("JournalEntryID") = JournalEntryToCopyToCtl.Value
    TopicRecord.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
    TopicRecord.Update
Next SelectedTopic
TopicRecord.Close
Set TopicRecord = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

首先,你的Dims不会像你期望的那样工作。使用:

Dim JournalEntrySourceRecord As Recordset
Dim JournalEntryDestinationRecord As Recordset
Dim TopicRecord As Recordset

其次,看起来你的ID包含在这里:

TopicRecord.Fields(Counter) 

主题是以某种方式包含它的查询。尝试专门指定字段和/或调试如下:

For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
    TopicRecord.Fields(Counter).Value = SelectedTopicsCtl.Column(Counter, SelectedTopic)
    Debug.Print Counter, TopicRecord.Fields(Counter).Name
Next Counter