MS Access VBA - 表单中的第一个记录在表单关闭时被覆盖?

时间:2018-02-15 00:46:26

标签: vba ms-access

我只是学习如何在Microsoft Access 2013中创建表单并使用VBA编程来控制,但我遇到了一个我不太了解的问题。

我创建了一个带有List Box的表单,其中源源自查询,该查询按从左到右的顺序包含以下字段:

   |ParentNumber|ParentName|ChildNumber|ChildName|
   |------------|----------|-----------|---------|
   |------------|----------|-----------|---------|
   |------------|----------|-----------|---------|

查询中的某些字段隐藏,列宽为 0"

我在Text Box下方{4} List Box对应相应的ParentNumber, ParentName, ChildNumber, and ChildName值。

当我在List Box中选择记录时,会将数据填充到相应的Text Box

首次加载表单时,会选择List Box中的第一行:

Private Sub Form_Load()

On Error Resume Next
    DoCmd.GoToRecord , , acFirst
    Me.List = Me.List.ItemData(0)
End Sub

问题是,如果我选择不同的行,然后关闭表单,重新打开表单,则表示第一行在表单关闭之前,List Box会被最后一个选定的行覆盖。

即使我在表单打开时开始选择最初的任何其他行,当表单关闭时,第一个行始终会被最后选定的行覆盖。

以下子例程处理Text Box数据的更新:

Private Sub List_AfterUpdate()
    Dim rowIndex As Integer
    rowIndex = Me.List.ListIndex

    Me.textBox_ParentNumber = Me.List.Column(3, rowIndex)
    Me.textBox_ParentName = Me.List.Column(4, rowIndex)
    Me.textBox_ChildNumber = Me.List.Column(6, rowIndex)
    Me.textBox_ChildName = Me.List.Column(7, rowIndex)
End Sub

我发现了一个与我有点类似的问题,但我尝试了建议的解决方案,但似乎没有效果:MS Access - First record in table is overwritten on form close

根据上面的代码,我完全不知道会导致什么原因。

我的问题是什么?

感谢。

3 个答案:

答案 0 :(得分:2)

很少有事情

Private Sub Form_Load()

    'remove this so you can see errors.
    'On Error Resume Next

    ' this goes to the first record of the *form*, not the list.
    ' you might want this, or not. 
    DoCmd.GoToRecord , , acFirst

    ' ItemData returns the data in the *bound column* of the list, 
    ' the data from one specific column. the list is set to that 
    ' data every time the form loads. not what you want; remove it.
    'Me.List = Me.List.ItemData(0)
End Sub

这应该摆脱这个问题。你接下来要做的是另一个问题。

答案 1 :(得分:0)

您的表单应绑定到记录集(表或查询)。

答案 2 :(得分:0)

我遇到了同样的问题,经过数小时的验证- 在我的情况下-问题是MainForm和SubForm(表)被绑定到同一记录集。我只是从MainForm取消绑定数据RS。