错误类型与回车和换行不匹配

时间:2016-03-20 13:01:15

标签: vba ms-access

我编写了一个函数来接收一个字符串,并将所有空格都删除掉,除了空格。当空格位于字符串的开头或结尾时,或者在另一个空格之后或之前,它们也会被删除。

例如 “_ a _____ a”将变为“a_a”。 (“_”代表空格)

我正在运行以下查询:

UPDATE table1
SET field1 = whitespace(field1)

由于某种原因,当字符串以回车符或换行符开头时,我收到类型不匹配错误。

Public Function whiteSpace(ByVal field As String) As String
    Dim i As Integer
    If (IsNull(field)) Then
        field = ""
        GoTo catchNulls
    End If
    field = RegexReplace(field, "(?=\s)[^ ]", " ")
    field = Trim(field)
    field = RegexReplace(field, "  +", " ")

catchNulls:
    whiteSpace = field
End Function 

Function RegexReplace(ByVal text As String, _
                      ByVal replaceWhat As String, _
                      ByVal replaceWith As String, _
                      Optional ByVal ignoreCase As Boolean = False) As String
    On Error GoTo catch
    Dim RE As Object
    Dim str As String

    str = Empty
    Set RE = CreateObject("vbscript.regexp")
    RE.ignoreCase = ignoreCase
    RE.pattern = replaceWhat
    RE.Global = True
    str = RE.Replace(text, replaceWith)
continue:
    RegexReplace = str
    Exit Function
catch:
    Call raiseError(Err.Number, Err.Source, Err.Description)
    GoTo continue
End Function

我尝试为Public Function whiteSpace(ByVal field As String) As String交换Public Function whiteSpace(ByVal field As Variant) As String并且我没有收到错误,但是有回车和换行符的字段保持不变。

1 个答案:

答案 0 :(得分:0)

您的正则表达式不正确。尝试使用此函数来规范化空格:

''
' Strips all the white-spaces from a string and replaces any sequence
' of white-space characters by a single space.
''
Function NormalizeSpace(text As String) As String
  Static re As Object
  If re Is Nothing Then
    Set re = CreateObject("VBScript.RegExp")
    re.Global = True
    re.Pattern = "\s+"
  End If
  NormalizeSpace = VBA.Trim$(re.replace(text, " "))
End Function