【问题标题】:Doing a compare between field and variable in MS access - does not find match在 MS 访问中比较字段和变量 - 找不到匹配项
【发布时间】:2020-07-13 19:07:18
【问题描述】:

我正在尝试删除 MS ACCESS 中的重复记录。 我创建了一个按字段名称排序的查询。

我有通过查询运行的 VBA 代码,然后当找到匹配项时,它会删除记录 - 但是它没有获取匹配项。

我的代码如下:

Dim db As DAO.Database
Dim recIn As DAO.Recordset
Dim strFieldName1 As Variant
Dim strFieldDescr2 As Variant
Dim strDomainCat3 As Variant
Dim strBusinessTerm4 As Variant
Dim strtableName5 As Variant
Dim lngRecordsDeleted As Variant

lngRecordsDeleted = 0
Set db = CurrentDb()
 Set recIn = db.OpenRecordset("qryMyRecords")  
 If recIn.EOF Then
 MsgBox ("No Input Records")
 recIn.Close
 Set recIn = Nothing
 Set db = Nothing
 Exit Sub
End If
Do
  If recIn!FieldName = strFieldName1 And _
     recIn!FieldDescr = strFieldDescr2 And _
     recIn!DomainCatID = strDomainCat3 And _
     recIn!BusinessTermID = strBusinessTerm4 And _
     recIn!TableID = strtableName5 Then
     recIn.Delete
     lngRecordsDeleted = lngRecordsDeleted + 1

 Else

   strFieldName1 = recIn!FieldName
   strFieldDescr2 = recIn!FieldDescr
   strDomainCat3 = recIn!DomainCatID
   strBusinessTerm4 = recIn!BusinessTermID
   strtableName5 = recIn!TableID

  End If
recIn.MoveNext
Loop Until recIn.EOF
recIn.Close
Set recIn = Nothing
 Set db = Nothing
MsgBox ("You Deleted " & lngRecordsDeleted & " Records")

End Sub

我的 StrFieldname1,到 StrTablename5 确实填充(在 else 语句之后)

但是当我第二次进行比较时

If recIn!FieldName = strFieldName1 And _
     recIn!FieldDescr = strFieldDescr2 And _
     recIn!DomainCatID = strDomainCat3 And _
     recIn!BusinessTermID = strBusinessTerm4 And _
     recIn!TableID = strtableName5 Then
     recIn.Delete
     lngRecordsDeleted = lngRecordsDeleted + 1

即使值相同,它也会移动到 else 语句,并且永远不会删除记录。

现在我怀疑这可能是因为我将变量声明为 VARIANT 类型,但如果我使用任何其他类型,则代码每次在查询中达到 NULL 值时都会失败,并且在某些情况下,任何查询中的字段可以并且将为空。 任何建议将不胜感激

【问题讨论】:

  • 在 MS ACCESS 中删除重复记录时,您有几个选择 - 尝试使用此链接解决您的问题 - databasejournal.com/features/msaccess/article.php/3077791/… 如果您遇到 NULL 值问题,您可以使用Access 中的NZ 函数将任何NULL 值转换为其他值。例如NZ(<<fieldname>>, "") - 将所有 NULL 值转换为空字符串。

标签: ms-access vba


【解决方案1】:

要扩展 Justin 所说的内容,请在您的主要 If 语句中使用 Nz 函数,如下所示:

If Nz(recIn!FieldName, "") = strFieldName1 And _
   ...
Else
   strFieldName1 = Nz(recIn!FieldName, "")
   ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2013-01-12
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多