使用 vba 更改字段的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41804156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:56:06  来源:igfitidea点击:

change a field's value with vba

vbams-accessaccess-vba

提问by Jan Willem van Gurp

I want to change a date in a specific table to today's date by clicking a button in a related form. So all the button does is changing the date in a certain field in my db. Is there a simple way to do this with VBA?

我想通过单击相关表单中的按钮将特定表中的日期更改为今天的日期。所以按钮所做的就是更改我数据库中某个字段中的日期。有没有一种简单的方法可以用 VBA 做到这一点?

I'm pretty much new to MS Access and VBA coding, so this might be a simple question but it kinda drives me crazy.

我对 MS Access 和 VBA 编码非常陌生,所以这可能是一个简单的问题,但它有点让我发疯。

Thank you very much in advance

非常感谢您提前

*Update

*更新

Well I wrote this in my VBA code:

好吧,我在我的 VBA 代码中写了这个:

CurrentDb.Execute "UPDATE Machines SET LastMaintenance = Date() WHERE MachineID = MachineID.Value" With "Machines" being my table, "LastMaintenance" the column containing the date that has to be changed into today's date, "MachineID" the name of the record and "MachineID.Value" the name of the textbox bound to that same record.

CurrentDb.Execute "UPDATE Machines SET LastMaintenance = Date() WHERE MachineID = MachineID.Value" 以 "Machines" 为我的表,"LastMaintenance" 包含必须更改为今天日期的日期的列,"MachineID" 的名称记录和“MachineID.Value”绑定到同一记录的文本框的名称。

So is there anything wrong with this code? Because when I click the button I getthis annoying error: "Not enough parameters. 1 expected."

那么这段代码有什么问题吗?因为当我点击按钮时,我得到这个恼人的错误:“没有足够的参数。1 预期。”

回答by Andre

The most straightforward way is to run a UPDATE query.

最直接的方法是运行 UPDATE 查询。

CurrentDB.Execute "UPDATE someTable SET someDate = Date() WHERE stuff = 47"

回答by Steve W

When performing an update query, you'll want to be cognizant of the datatype for each field, as you will have to present it differently in your code. Also, you will need to break up your string text when inserting a variable. In your current state, it's looking for a MachineID field with 'MachineID.value' as its contents. Try this:

执行更新查询时,您需要了解每个字段的数据类型,因为您必须在代码中以不同方式呈现它。此外,您需要在插入变量时拆分字符串文本。在您当前的状态下,它正在寻找内容为“MachineID.value”的 MachineID 字段。尝试这个:

CurrentDb.Execute "UPDATE Machines SET LastMaintenance = Date() WHERE MachineID = " & MachineID.Value

回答by Gustav

If

如果

a button in a related form

相关表单中的按钮

means a form bound to that table displaying the record you wish to update, use the OnClickevent of the button:

表示绑定到该表的表单,显示您希望更新的记录,使用按钮的OnClick事件:

Private Sub NameOfYourButton_Click()

    Me![NameOfYourDateField].Value = Date
    ' Optionally, save the record at once:
    Me.Dirty = False

End Sub