问题描述
我正在尝试比较 Access 2016 中的两个不同列。两者都包含人名,但两者的顺序不同。
姓名
哈里斯,凯莎
约翰·巴纳汉
加西亚西尔维拉,安娜
NameFormat2
凯莎·梅琳达·哈里斯
约翰 C.巴纳汉
安娜·露西亚·加西亚·西尔维拉
目前,当比较这两列时,它们都会标记,因为它们不是完全匹配的。
第一列中的名称总是比第二列中的全名短。
有没有办法,无论是查询还是 VBA 或任何其他选项,说如果第一列中的所有名称都包含在第二列中,那么它是匹配的并继续前进?
任何帮助将不胜感激!
谢谢, 罗伯特
解决方法
不确定这是否是最好的方法,但您可以创建一个 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
来处理诸如“.”之类的内容。在名称中。
在给出的示例中,前两个(Keisha Harris 和 John Banaghan)返回 true,最后一个(Ana Silveira)返回 false,因为在她的姓氏(Silbeira)的第二个实例中似乎存在拼写错误。
问候,