vba 如何检查Access表中是否存在值

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

How to check if value exists in Access table

vbams-access

提问by octsim

I'm getting an error message while trying to check if a serial number already exists in my table (Access 2010).

我在尝试检查表 (Access 2010) 中是否已存在序列号时收到错误消息。

Here's the code I'm using:

这是我正在使用的代码:

If CurrentDb.OpenRecordset("Select count(*) from Table_Name where vSerial='" & Forms!Form_Name!vSerial & "';").Fields(0) > 0 Then
MsgBox ("Serial number already in use")
Else
Me.ctrl_register.Pages(1).Enabled = True
Me.ctrl_register.Pages(1).SetFocus
End If

What am I doing wrong?

我究竟做错了什么?

I'm using the same code with 2 different tables and I can't find the difference between them. The only difference between the tables is the number of data in them.

我在 2 个不同的表中使用相同的代码,但我找不到它们之间的区别。表之间的唯一区别是其中的数据数量。

Could someone point me in the right direction?

有人能指出我正确的方向吗?

The error I get is a runtime error 3464 in Access - data type missmatch in criteria expression.

我得到的错误是 Access 中的运行时错误 3464 - 条件表达式中的数据类型不匹配。

The variable vSerial is defined as a number.

变量 vSerial 被定义为一个数字。

Thanks in advance!

提前致谢!

采纳答案by Irfan Shaikh

vSerial is integer value and you have used '' in your query, remove them. Quotes are used for string values.

vSerial 是整数值,您在查询中使用了 '' ,请将其删除。引号用于字符串值。

If CurrentDb.OpenRecordset("Select count(*) from Table_Name where vSerial=" & Forms!Form_Name!vSerial & ";").Fields(0) > 0 Then
    MsgBox ("Serial number already in use")
Else
    Me.ctrl_register.Pages(1).Enabled = True
    Me.ctrl_register.Pages(1).SetFocus
End If

回答by poilane

You can also use that method :

您也可以使用该方法:

If DCount("vSerial", "from Table_Name", "vSerial=" & Forms!Form_Name!vSerial)  > 0 Then
    MsgBox ("Serial number already in use")
Else
    Me.ctrl_register.Pages(1).Enabled = True
    Me.ctrl_register.Pages(1).SetFocus
End If