【问题标题】:Access VBA to Update Table Record访问 VBA 更新表记录
【发布时间】:2020-08-17 18:55:12
【问题描述】:

我正在尝试将代码分配给 MS Access 中将更新表记录的按钮。单击按钮时,我希望它在附近的列表框(List26)中引用用户更新的项目编号,在表(资产)中查找匹配的项目编号字段,然后更改字段(所有者)记录为空。

我一直在挖掘并发现了一些关于 DAO 记录集的逻辑,但我对 VBA 的熟悉程度不足以正确设置它或知道这是否是正确的路径。以下是我到目前为止所做的:

Private Sub Check_In_Device_Click()
    Dim rec As DAO.Recordset

'Table1 called "Assets"
    Set rec = CurrentDb.OpenRecordset("SELECT * FROM Assets")
    
'if the data in List26 matches an Item# in Asset table...
    If [Item].value = [List26].value Then
    rec.MoveFirst
    rec.Edit
'change Owner field to null
    rec![Owner].value = ""
    rec.Update
    rec.Close
    End If
End Sub

【问题讨论】:

    标签: vba ms-access button


    【解决方案1】:

    Item 可能是数字,并使用 Null 来空白一个字段,因此尝试:

    Private Sub Check_In_Device_Click()
    
        Dim rec As DAO.Recordset
    
        ' Table1 called "Assets"
        Set rec = CurrentDb.OpenRecordset("SELECT * FROM Assets")
    
        If rec.RecordCount > 0 Then    
            ' If the data in List26 matches an Item# in Asset table...
            rec.MoveFirst
            rec.FindFirst "Item = '" & Me!List26.Value & "'"
            If Not rec.NoMatch Then
                ' Item found.
                rec.Edit
                ' Change Owner field to null
                rec!Owner.Value = Null
                rec.Update
            End If
        End If
        rec.Close
    
    End Sub
    

    【讨论】:

    • 谢谢! “项目”字段仍设置为文本,但使用 NULL 使其通过。
    • 好的,改变了。所以答案是?
    【解决方案2】:

    OpenRecordset 获取表/查询名称和类型,您需要打开为 dbOpenDynaset 才能使用.findfirst

    确保您的列表框设置为使用Bound Column 属性返回正确的值(默认值可能是记录的唯一键)。

    应该这样做:

    Private Sub Check_In_Device_Click()
        Dim rec As DAO.Recordset
        
        Set rec = CurrentDb.OpenRecordset("Assets", dbOpenDynaset)
        
        With rec
            .FindFirst "[Item] Like '" & List26.Value & "'"
            .Edit
            ![Owner] = ""
            .Update
            .Close
        End With
        
    End Sub
    

    如果你想遍历整个记录集,你可以使用:

        Dim rec As DAO.Recordset
        
        Set rec = CurrentDb.OpenRecordset("Assets", dbOpenDynaset)
        
        With rec
            .MoveFirst
            Do Until .EOF
                If ![Item] Like List26.Value Then
                    .Edit
                    ![Owner].value = Null
                    .Update
                End If
                .MoveNext
            Loop
            .Close
        End With
    

    【讨论】:

    • 谢谢!这清理了很多,并在调试时给了我更好的响应。最终仍然收到针对 ![Owner] 字段的数据对话错误,但切换到 NULL 并且现在可以开始了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2014-05-12
    • 2021-08-10
    相关资源
    最近更新 更多