【发布时间】:2021-10-14 04:59:00
【问题描述】:
我正在使用 MS Access 2010。我正在尝试搜索表并根据名字和姓氏确定记录是否存在,如果记录存在则更新记录,如果不存在,则插入新记录记录。我没有收到任何错误,但即使我输入了我知道表中不存在的名称,我的记录数也始终为 1。
Private Sub txtSearchFirstName_Exit(Cancel As Integer)
Dim strSQL As String
Dim db As Database
Dim rs As DAO.Recordset
Dim recordCount As Long
Set db = CurrentDb
Set rs = Nothing
Stop
''Check if a keyword entered or not
If IsNull(Me.txtSearchlastName) = "" Then
MsgBox "Please type in your search keyword.", vbOKOnly, "Keyword Needed"
Else
strSQL = "SELECT COUNT(*) " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If (rs.BOF And rs.EOF) Then
recordCount = 0
Else
rs.MoveLast
recordCount = rs.recordCount
End If
If recordCount > 0 Then MsgBox ("Record exists")
If recordCount = 0 Then MsgBox ("Record does not exist")
rs.Close
Set rs = Nothing
End If
End Sub
【问题讨论】:
-
记录集包含一条记录,其中一个字段向您显示与您的
WHERE条件匹配的tblBobbettesMarketBulletin_CustNum记录中的COUNT。如果没有匹配项,则记录集将包含一条在COUNT字段中为零的记录。在打开记录集后将Debug.Print rs.Fields(0).Value添加到您的代码中 --- 也许这将有助于澄清情况。 -
谢谢,这很有帮助
-
谨防 SQL 注入。如果有人输入 Thomas “Tommy”的名字,查询将失败。
标签: vba ms-access ms-access-2010