使用 VBA 模块从 Access 中的表单获取文本值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9383468/
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-08 12:37:19  来源:igfitidea点击:

Get a text value from a form in Access using a VBA module

formsms-accessvba

提问by helium1988

I currently want to get a value from a form to set it in an SQL query I make in a module under Access using VBA. I tried to use

我目前想从表单中获取一个值,以便在我使用 VBA 在 Access 下的模块中创建的 SQL 查询中设置它。我试着用

value = Forms![NameOfForm]![NameOfTextbox] 

sqlquery = "...." & value & "....."

It make an error (2450) saying it cannot found the specified form. How can I get the value of this textbox so I could use it in my module?

它会出错 (2450),说找不到指定的表单。如何获取此文本框的值以便在我的模块中使用它?

Thx

谢谢

采纳答案by HansUp

Modify your VBA code to ensure the form is open.

修改您的 VBA 代码以确保表单已打开。

DoCmd.OpenForm "NameOfForm"

That should prevent error #2450.

这应该可以防止错误 #2450。

Afterwards, you don't need to store the value of [NameOfTextbox] to a variable, then use that variable to build your SQL statement. You can use its value directly.

之后,您无需将 [NameOfTextbox] 的值存储到变量中,然后使用该变量来构建 SQL 语句。您可以直接使用它的值。

sqlquery = "SELECT * FROM YourTable " & _
"WHERE some_field = '" & Forms![NameOfForm]![NameOfTextbox] & "';"

Or embed a reference to the textbox itself (instead of the textbox's value) in the query.

或者在查询中嵌入对文本框本身的引用(而不是文本框的值)。

sqlquery = "SELECT * FROM YourTable " & _
"WHERE some_field = Forms![NameOfForm]![NameOfTextbox];"

I assumed some_field is a text data type field, so enclosed the textbox value with single quotes in the first query example. Notice the second example doesn't need the quotes because it refers to the textbox by name rather than its value.

我假设 some_field 是文本数据类型字段,因此在第一个查询示例中用单引号将文本框值括起来。请注意,第二个示例不需要引号,因为它是通过名称而不是值来引用文本框的。

However, should you continue with your original approach (storing the textbox value to a variable), don't name your variable "value" because value can be confused with a property of many objects.

但是,如果您继续使用原始方法(将文本框值存储到变量中),请不要将变量命名为“值”,因为值可能会与许多对象的属性混淆。