1

文字列を取得し、連続するスペースをそのまま残しながら、単一のスペースのすべての出現を削除するコードを

これは私が今持っているものですが、すべてのスペースを削除してダッシュに置き換えているだけです。

助けや指導をありがとう!

Sub Main
    'Nothing happens when the code executes the following string
    CombineText("Job           Hours        Pay   Labor %")

    'When the following executes it should look like this
    'Major-Group-Total     382       2,085.25
    CombineText("Major Group Total     382       2,085.25")
End Sub

Sub CombineText(searchString As String)   
    a = Len(searchString)

     For n = 1 To a    
        If Mid(searchString, n, 1) = Chr(32) Then
             searchString = Application.Substitute(searchString, Mid(searchString, n, 1), "-")
        End If
    Next n
End Sub
4

2 に答える 2

4
Function CombineText(sSearch As String) As String

    Dim i As Long
    Dim sReturn As String

    sReturn = sSearch

    For i = 2 To Len(sReturn) - 1
        If Mid$(sSearch, i, 1) = Space(1) And Mid$(sSearch, i - 1, 1) <> Space(1) And Mid$(sSearch, i + 1, 1) <> Space(1) Then
             Mid$(sReturn, i, 1) = "-"
        End If
    Next i

    CombineText = sReturn

End Function

?combinetext("Major Group Total     382       2,085.25")
Major-Group-Total     382       2,085.25
?combinetext("Job           Hours        Pay   Labor %")
Job           Hours        Pay   Labor-%
于 2013-09-27T21:16:03.807 に答える
1

RegExp文字をループするのではなく、a を使用して 1 回のショットでこれを行うこともできます。

Function CleanStr(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "(\S)\s(?=\S)"
.Global = True
CleanStr = .Replace(strIn, "$1-")
End With
End Function

Sub Test()
Debug.Print CleanStr("Job           Hours        Pay   Labor %")
Debug.Print CleanStr("Major Group Total     382       2,085.25")
End Sub
于 2013-09-29T02:09:54.410 に答える