vba 如何使用 Access 的 OpenRecordset 使用其数字键字段获取记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15858000/
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
How to use Access' OpenRecordset to get a record using its numeric key field?
提问by Josell
I have a problem in Access 2010 VBA trying to read a record from table to write it into TextBoxes.
我在尝试从表中读取记录以将其写入文本框的 Access 2010 VBA 中遇到问题。
My table is "Products" and its ProductID field is numeric. I used this method before, but it just works for text fields, not for numericfields (ProductID is autonumber).
我的表是“产品”,它的 ProductID 字段是数字。我以前用过这个方法,但它只适用于文本字段,不适用于数字字段(ProductID 是自动编号)。
Private Sub GetProduct(ID As TextBox, Name As TextBox, Price As TextBox)
If ID <> "" Then
Set db = CurrentDb
Set rs = db.OpenRecordset("Productos", dbOpenDynaset)
'PROBLEM IS HERE
rs.FindFirst "ProductID=" & "'" & ID & "'"
If rs.NoMatch Then
MsgBox "The producto doesn't exist."
Price = ""
Name = ""
Else
Name = rs!ProductName
Price = rs!Price
End If
rs.Close
Set rs = Nothing
Set db = Nothing
End If
End Sub
Please, help me. This is for a Final Proyect and I don't know other, but this method. Please help me.
请帮我。这是一个最终项目,我不知道其他的,但是这个方法。请帮我。
回答by Rokhi
Good to see you figured it out. The problem is that ProductID is numeric and your code specifically tests for a text field
很高兴看到你想通了。问题是 ProductID 是数字,您的代码专门测试文本字段
rs.FindFirst "ProductID=" & "'" & ID & "'"
putting a single quote each side of the parameter makes Access parse the parameter as a string.
在参数的每一侧放置一个单引号使 Access 将参数解析为字符串。
If ID is 123, this will read
如果 ID 是 123,这将读取
rs.FindFirst "ProductID='123'"
and you get a type error
然后你得到一个类型错误
回答by Josell
I found a simple solution!
我找到了一个简单的解决方案!
rs.FindFirst "ProductoID=" & ID