2016-03-20 7 views
0

文字列を受け取って空白を除くすべての空白を除いて返す関数を作成しました。スペースが文字列の先頭または末尾にある場合、または別のスペースの後または前にスペースがある場合は、それらも消去されます。キャリッジリターンと改行によるエラータイプの不一致

Ex。"_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 Variant) As StringためPublic Function whiteSpace(ByVal field As String) As Stringを交換しようと、私はエラーを取得できませんでしたが、キャリッジリターンとラインフィードを持つフィールドが同じとどまりました。

+0

「field1」の文字列値を取得します。2.関数を介して文字列値を操作します。3. ' field1'を新しい値で置き換えます。 – Ambie

答えて

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 
+0

ありがとうございますが、先頭と末尾の空白を削除する必要があります**空白を空白にしない** **空白**を除いて、**空白のシーケンスを空白で置き換えてください。 – MJH

+0

私の説明は誤解を招きます。私はそれを更新します。 –

+0

あなたのコードも説明してください。ありがとうございました。 – MJH

関連する問題