質問

In MS Access I've tried to use:

UPDATE Table SET FieldName= REPLACE(FieldName, '\s+', '\s');

to remove multiple spaces from a field, but it doesn't work.

役に立ちましたか?

解決

As mentioned in the comments to the question, the Replace() function does not support regular expressions. However, you could accomplish your goal with the following VBA code:

Option Compare Database
Option Explicit

Sub RemoveMultipleSpaces()
    Dim cdb As DAO.Database
    Set cdb = CurrentDb
    Do While DCount("FieldName", "TableName", "FieldName LIKE ""*  *""") > 0
        cdb.Execute "UPDATE TableName SET FieldName = Replace(FieldName,""  "","" "")"
    Loop
    Set cdb = Nothing
End Sub

edit re: comment

Alternatively, you could use the following code which uses regular expressions to find the replacement candidates:

Option Compare Database
Option Explicit

Public Function RegexReplace( _
        originalText As Variant, _
        regexPattern As String, _
        replaceText As String, _
        Optional GlobalReplace As Boolean = True) As Variant
    Dim rtn As Variant
    Dim objRegExp As Object  ' RegExp

    rtn = originalText
    If Not IsNull(rtn) Then
        Set objRegExp = CreateObject("VBScript.RegExp")
        objRegExp.Pattern = regexPattern
        objRegExp.Global = GlobalReplace
        rtn = objRegExp.Replace(originalText, replaceText)
        Set objRegExp = Nothing
    End If
    RegexReplace = rtn
End Function

Usage example:

RegexReplace("This is     a test.","\s+"," ")

returns

This is a test.

You would use it in a query like this:

UPDATE TableName SET FieldName = RegexReplace(FieldName,'\s+',' ')

他のヒント

This function remove multiple spaces and also tabs, new line symbols etc.

Public Function removeObsoleteWhiteSpace(FromString As Variant) As Variant
  If IsNull(FromString) Then 'handle Null values
    removeObsoleteWhiteSpace = Null
    Exit Function
  End If
  Dim strTemp As String
  strTemp = Replace(FromString, vbCr, " ")
  strTemp = Replace(strTemp, vbLf, " ")
  strTemp = Replace(strTemp, vbTab, " ")
  strTemp = Replace(strTemp, vbVerticalTab, " ")
  strTemp = Replace(strTemp, vbBack, " ")
  strTemp = Replace(strTemp, vbNullChar, " ")
  While InStr(strTemp, "  ") > 0
    strTemp = Replace(strTemp, "  ", " ")
  Wend
  strTemp = Trim(strTemp)
  removeObsoleteWhiteSpace = strTemp
End Function
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top