如何从字符串VBA中删除单个空格(不删除连续的空格)

时间:2013-09-27 21:02:45

标签: string vba

我正在编写代码来取一个字符串并删除所有出现的单个空格,同时保留连续的空格。

这就是我现在所拥有的,但它只是移除所有空格并用短划线替换它们。

感谢您提供任何帮助或指导!

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

2 个答案:

答案 0 :(得分: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-%

答案 1 :(得分:1)

您也可以使用RegExp一次性执行此操作,而不是遍历字符

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