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

您也可以使用 aRegExp在单次拍摄中执行此操作,而不是循环遍历角色

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 回答