3

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

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

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

等等等等...

在继续使用上述数据字段添加新记录之前,我需要创建一个检查表,以确定名称、城市和邮政编码的组合是否已经存在。如果他们这样做,我希望它退出 Sub;否则继续宏的其余部分。

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

4

2 回答 2

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
于 2013-08-05T19:18:38.047 回答
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
于 2013-08-05T18:08:43.817 回答