You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Access VBA添加MAC用户时数据表出现重复条目问题排查

Access窗体添加记录重复问题解决方法

问题现象

通过Access窗体添加新MAC用户时,数据表Tbl_2_MAC会生成2条重复条目,但仅能在C:\Users\Desktop\MACs\路径下创建1个对应文件夹。此前无VBA直接录入数据时无此问题,新建窗体后问题依旧。

问题原因

核心原因是窗体数据源绑定与VBA代码的双重插入冲突:

  • VBA代码已通过Recordset对象手动向表中插入一条记录;
  • 若窗体的RecordSource属性设置为Tbl_2_MAC,且输入控件绑定到表字段,点击按钮时窗体会自动保存当前输入的记录,导致同一条数据被插入两次。

解决方案

方案一:取消窗体数据源绑定(推荐)

  1. 打开窗体设计视图;
  2. 选中窗体,在属性窗口中将RecordSource属性清空;
  3. 检查所有输入控件(如txtMAC、txtLevel4等),清空它们的ControlSource属性;
  4. 保存窗体后重新测试,此时仅VBA代码负责插入记录,不会产生重复。

方案二:保留绑定并阻止窗体自动保存

若需保留窗体数据源绑定,可在VBA代码末尾添加Me.Undo,撤销窗体自动生成的重复记录:

Private Sub cmd_AddMAC_Click()
    'Create new MAC and Folder
    Dim rstMAC As Recordset
    Set rstMAC = CurrentDb.OpenRecordset("Tbl_2_MAC", dbOpenDynaset)

    With rstMAC
        .AddNew
        !MAC = Me.txtMAC.Value
        !Level4 = Me.txtLevel4.Value
        !Level5 = Me.txtLevel5.Value
        !PrimeOrganization = Me.txtPrimeSection.Value
        !SubOrganization = Me.txtSubSection.Value
        'Add Additonal Fields here - see above !NAME = Me.txtName.Value
        .Update
        .MoveLast 'move to the last record to get the newly created ID
        Dim lngIDMainMAC As Long
        lngIDMainMAC = !IDMainMAC ' get the value of the newly created ID
    End With

    ' Create new folder on drive
    Dim strFolderPath As String
    strFolderPath = "C:\Users\Desktop\MACs\" & Me.PrimeSection.Value & "," & Me.txtLevel5.Value & " (" & lngIDMainMAC & ")"

    If Dir(strFolderPath, vbDirectory) = "" Then
        MkDir strFolderPath
        MsgBox "MAC Folder Created Successfully!"
    Else
        MsgBox "Folder already exists"
    End If

    ' 撤销窗体自动保存的重复记录
    Me.Undo

    'CleanUp
    rstMAC.Close
    Set rstMAC = Nothing
End Sub

内容的提问来源于stack exchange,提问作者styx lykin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:47:36