首页 > 解决方案 > MS Access:比较匹配的两列 - 不同顺序的名称

问题描述

我正在尝试比较 Access 2016 中的两个不同列。两者都包含人名,但两者的顺序不同。

姓名
哈里斯、
凯莎·巴纳汉、约翰·
加西亚·西尔维拉、安娜

名称格式2

凯莎梅琳达哈里斯

约翰·C·巴纳汉

安娜·露西亚·加西亚·西尔维拉

目前,在比较这两列时,它们都会标记,因为它们不是完全匹配的。

第一列中的名称总是比第二列中的全名短。

有没有办法,无论是查询还是 VBA 或任何其他选项,说如果第一列中的所有名称都包含在第二列中,那么它是匹配并继续前进?

任何帮助将不胜感激!

谢谢,罗伯特

标签: ms-accesscompare

解决方案


不确定这是否是最好的方法,但您可以创建一个 VBA 函数,通过将两个字段拆分为数组并循环它们来进行检查。像这样的东西似乎有效:

Function fCompareNames(strName1 As String, strName2 As String) As Boolean
    On Error GoTo E_Handle
    Dim astrName1() As String
    Dim astrName2() As String
    Dim intLoop1 As Integer
    Dim intLoop2 As Integer
    Dim intNames As Integer
    Dim intMatch As Integer
    strName1 = Replace(strName1, ",", "")
    strName2 = Replace(strName2, ",", "")
    astrName1 = Split(strName1, " ")
    astrName2 = Split(strName2, " ")
    intNames = UBound(astrName1) - LBound(astrName1) + 1
    For intLoop1 = LBound(astrName1) To UBound(astrName1)
        For intLoop2 = LBound(astrName2) To UBound(astrName2)
            If astrName1(intLoop1) = astrName2(intLoop2) Then
                intMatch = intMatch + 1
                Exit For
            End If
        Next intLoop2
    Next intLoop1
    If intMatch = intNames Then fCompareNames = True
fExit:
    On Error Resume Next
    Exit Function
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "fCompareNames", vbOKCancel + vbCritical, "Error: " & Err.Number
    Resume fExit
End Function

您可能需要添加一些额外Replace的 s 来处理诸如“.”之类的事情。在名字里。

在给出的示例中,前两个(Keisha Harris 和 John Banaghan)返回 true,最后一个(Ana Silveira)返回 false,因为她的第二个姓氏(Silbeira)似乎有拼写错误。

问候,


推荐阅读