Access 2010 - 在添加新记录之前检查记录集中的数据

时间:2013-08-05 17:30:54

标签: access-vba ms-access-2010

我是Access的新手,所以请耐心等待。

我有一个允许我向表中添加新数据的表单

ID  | Name |  City  | Zip Code
1   | John | Newark | 12340
2   | Alex | Boston | 98760

等等......

在继续使用上述数据字段添加新记录之前,我需要创建一个检查,查看该表以确定Name,City和Zip Code的组合是否已存在。如果他们这样做,我希望它退出Sub;否则继续使用宏的其余部分。

我一直在寻找使用某种形式的OpenRecordset命令构建它,但我不知道从哪里开始。有人能指出我正确的方向吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我刚刚写了这段代码来重新创建你的情况,它运行良好。您只需要在查询中重命名列和表。

Dim strSQL As String
Dim qdf As QueryDef

'if these columns are not text change to approriate type
strSQL = "PARAMETERS [NameToCheck] Text(255),[CityToCheck] Text(255),[Zip] Text(255); " 

'change table name and column names here
strSQL = strSQL & "SELECT Count(*) FROM address " _ 
                & "WHERE FName = [NameToCheck]  AND City = [CityToCheck] AND ZipCode = [Zip];"

Set qdf = CurrentDb.CreateQueryDef("", strSQL)
qdf("NameToCheck") = txtName.Value 'change to that textfield on form
qdf("CityToCheck") = txtCity.Value 'change to that textfield on form
qdf("Zip") = txtZipCode.Value 'change to that textfield on form

If qdf.OpenRecordset(dbOpenSnapshot)(0) > 0 Then
    MsgBox "This record is already in the database"
Else
    'Insert statement goes here.
End If

答案 1 :(得分:0)

如果您想按照要求使用记录集,那么您需要使用SQL语句来选择全部或使用它来按名称查找内容。

Dim myR as Recordset
Dim strSQL as String

'run a SQL statement to select a record with the same info
strSQL = "SELECT [Name], [City], [Zip Code] FROM table_name_here " & _
         "WHERE [Name] = '" & form_control_name & "' " & _
         "AND [City] = '" & form_control_city & "' " & _
         "AND [Zip Code] = '" & form_control_zip & "'"

'set your recordset to the SQL statment
Set myR = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)

'if your count is greater than 0, then you'll have a duplicate
If myR.RecordCount > 0 then
    MsgBox "This already exists"
Else
    MsgBox "All clear"
End if

Set myR = Nothing
相关问题