【问题标题】:MSAccess - Requery a Subform After Insert?MS Access - 插入后重新查询子表单?
【发布时间】:2017-03-09 22:26:58
【问题描述】:

背景:

我有一个子表单(数据表),我在更新事件后使用数据表复选框更新:

  1. 我克隆了单击的记录并通过插入查询插入到引用的表中
  2. 我修改原始记录以通过更新查询与插入的记录区分开来

为了避免 RecordLock 投诉,我在上述每个操作之后插入:SendKeys "+{Enter}", True 以保存更新 - 有没有更好的方法来做到这一点?

接下来我需要重新查询子表单以显示新插入的记录并使用书签 (?) 来保留原始记录的光标位置(插入的记录将相邻)。子表单数据表记录集基于查询。

问题:

  1. 在子表单的 afterupdate 事件中,使用 Forms![ParentForm].[SubForm].Form.Requery 不会产生错误,但会打开代码窗口,其中行以黄色突出显示。

  2. 下一次尝试,在子表单的 afterupdate 事件中,我尝试使用 Forms![ParentForm].[SubForm].Form.Requery 将焦点设置到 ParentForm 上的控件,但我得到了类似的 ~silent error ~ 如上所述。

  3. 从同一子表单中请求子表单的正确方法是什么?

谢谢!

【问题讨论】:

    标签: ms-access


    【解决方案1】:

    你让自己太难了。以下是如何通过单击按钮复制记录。无锁、无查询、自动更新表单:

    Private Sub btnCopy_Click()
    
      Dim rstSource   As DAO.Recordset
      Dim rstInsert   As DAO.Recordset
      Dim fld         As DAO.Field
    
      If Me.NewRecord = True Then Exit Sub
    
      Set rstInsert = Me.RecordsetClone
      Set rstSource = rstInsert.Clone
      With rstSource
        If .RecordCount > 0 Then
          ' Go to the current record.
          .Bookmark = Me.Bookmark
          With rstInsert
            .AddNew
              For Each fld In rstSource.Fields
                With fld
                  If .Attributes And dbAutoIncrField Then
                    ' Skip Autonumber or GUID field.
                  ElseIf .Name = "SomeFieldToHandle" Then
                    rstInsert.Fields(.Name).Value = SomeSpecialValue
                  ElseIf .Name = "SomeOtherFieldToHandle" Then
                    rstInsert.Fields(.Name).Value = SomeOtherSpecialValue
                  ElseIf .Name = "SomeFieldToSkip" Then
                    ' Leave empty or with default value.
                  ElseIf .Name = "SomeFieldToBlank" Then
                    rstInsert.Fields(.Name).Value = Null
                  Else
                    ' Copy field content.
                    rstInsert.Fields(.Name).Value = .Value
                  End If
                End With
              Next
            .Update
            ' Go to the new record and sync form.
            .MoveLast
            Me.Bookmark = .Bookmark
            .Close
          End With
        End If
        .Close
      End With
    
      Set rstInsert = Nothing
      Set rstSource = Nothing
    
    End Sub
    

    如果按钮放置在父窗体上,请将Me 替换为:

    Me!NameOfYourSubformControl.Form
    

    AddNewUpdate 之间,您可以修改和插入代码来调整一些不应只是复制的字段的值。

    【讨论】:

    • 古斯塔夫 - 谢谢!我会看那个例子,尤其是书签部分。在我的实例中,该事件是由子表单数据表上的复选框与父表单上的按钮上的 afterupdate 事件触发的。你怀疑有什么问题吗?
    • 古斯塔夫 - 哇。完美运行,甚至具有调整克隆的内置选项。如果我可以对您的回答 +10 投票,我会的! - 谢谢!
    • 太棒了!奇怪的是,这种自适应技术非常适合 Access,但您很少会遇到类似的代码。
    • 古斯托夫,如果我可以再强加一次的话。有什么建议可以在.Update 之后重新排序记录集,但保留书签?插入的记录出现在数据表的底部,而不是在其他记录中排序。事后简单的重新排序让我获得了第一条记录。
    • 没关系 - 明白了:重新排序,然后:Me.RecordsetClone.FindFirst
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多