如何通过忽略 .' 等其他字符来比较 MS Access 中的两列
例如以下两列数据应该计数
Col1 Col2
"adA.'kd," adA.kd
感谢您的回复
谢谢
如何通过忽略 .' 等其他字符来比较 MS Access 中的两列
例如以下两列数据应该计数
Col1 Col2
"adA.'kd," adA.kd
感谢您的回复
谢谢
如果您打算使用 Regex,那么您可以在替换中使用字符类\W
(相当于[^\w]
),表示任何非单词字符。这不包括数字和下划线。如果您也想替换这些,请考虑[^A-Za-z]
;也就是说,任何不是字母的东西。
访问函数包括Replace
但它不是很有用,因为它不允许我们指定一组要替换的字符。如果您使用 Access Query 来执行比较,那么您可以创建一个可以在查询中使用的 VBA 函数,类似于以下内容。
Function GetAlpha(strInput As String) As String
'Returns a string containing only the letters from the input
Dim strCheck As String
Dim i As Integer
Dim iLen As Integer
Dim strOutput As String
Dim ch As String
strCheck = strInput 'remember the original input
strInput = LCase(strInput) 'ignore case temporarily
iLen = Len(strInput)
For i = 1 To iLen
ch = Mid(strInput, i, 1)
If ch >= "a" And ch <= "z" Then
'if a letter, build a string using the original letter from the input
strOutput = strOutput & Mid(strCheck, i, 1)
End If
Next i
GetAlpha = strOutput
End Function
在 Access 查询中,您将创建一个表达式,例如
IIF(GetAlpha([Field1])=GetAlpha([Field2]),"Same","Different")
虽然访问忽略大小写。如果您不想区分大小写,那么您也可以使用StrComp()
,或者修改我的函数以包含两个(字符串)参数并返回一个布尔值。您可以使用以下命令,而不是修改函数:
Function CompareAlpha(strInput1 As String, strInput2 As String) As Boolean
'case-insensitive comparison of the letters of two strings
CompareAlpha = (StrComp(GetAlpha(strInput1), GetAlpha(strInput2), _
vbBinaryCompare) = 0)
End Function
以下函数与上面的 GetAlpha() 完全相同,但可能稍微简洁一些:
Function GetAlpha(strInput As String) As String
Dim i As Integer
Dim iLen As Integer
Dim strOutput As String
Dim ch As String
iLen = Len(strInput)
For i = 1 To iLen
ch = LCase(Mid(strInput, i, 1))
If ch >= "a" And ch <= "z" Then
strOutput = strOutput & Mid(strInput, i, 1)
End If
Next i
GetAlpha = strOutput
End Function
编辑:以下类似函数检查字符串是否仅包含字母。(我已经包含它以防它对其他人有用。)
Function CheckAlpha(strInput As String) As Boolean
Dim strCheck As String
Dim i As Integer
Dim iLen As Integer
Dim strOutput As String
Dim ch As String
strCheck = strInput 'store the original input to compare later
strInput = LCase(strInput) 'temporarily ignore case
iLen = Len(strInput)
For i = 1 To iLen
ch = Mid(strInput, i, 1)
If ch >= "a" And ch <= "z" Then
'construct a string of only the letters from the original input
strOutput = strOutput & Mid(strCheck, i, 1)
End If
Next i
'is the letters-only version the same as the original input?
CheckAlpha = (strCheck = strOutput)
'use StrComp() for case-sensitivity. That is, we could use StrComp() to
'check if all letters were upper, or lower, case.
End Function
已添加作为对评论的回应,如果数据可能包含 NULL 值,则以下修订将返回空字符串“”而不是Type Mismatch
错误。另一种方法是在调用 GetAlpha() 之前排除 NULL。
Function GetAlpha(varInput As Variant) As String
Dim i As Integer
Dim iLen As Integer
Dim strOutput As String
Dim ch As String
If IsNull(varInput) Then
GetAlpha = ""
Exit Function
End If
iLen = Len(varInput)
For i = 1 To iLen
ch = LCase(Mid(varInput, i, 1))
If ch >= "a" And ch <= "z" Then
strOutput = strOutput & Mid(varInput, i, 1)
End If
Next i
GetAlpha = strOutput
End Function