Excel VBA - 无法使用修剪和类似函数删除单词之间的额外空格

时间:2016-08-22 14:49:56

标签: excel vba excel-vba

我正在尝试使用VBA删除字符串中不必要的空格,但修剪功能似乎对我不起作用。我想在这个假设的例子中删除'End'和'Time'之间的额外空格。

Public Sub RemoveSpaces()

    Dim s As String: s = "START TIME: N/A END     TIME: N/A "

    s = Trim(s)

    Debug.Print s

    End Sub

enter image description here

5 个答案:

答案 0 :(得分:4)

最简单(也许是表现最佳)的方式是使用正则表达式:

'Requires reference to Microsoft VBScript Regular expressions
Private Function RemoveExtraSpace(inVal As String) As String
    With New RegExp
        .Pattern = "\s+"
        .Global = True
        RemoveExtraSpace = .Replace(inVal, " ")
    End With
End Function

Sub Example()
    Dim s As String
    s = "START TIME: N/A END     TIME: N/A "

    Debug.Print RemoveExtraSpace(s)
End Sub

后期绑定版本:

Private Function RemoveExtraSpace(inVal As String) As String
    With CreateObject("VBScript.RegExp")
        .Pattern = "\s+"
        .Global = True
        RemoveExtraSpace = .Replace(inVal, " ")
    End With
End Function

编辑:如果您需要多行注释,只需添加其他参数:

With New RegExp
    .Pattern = "\s+"
    .Global = True
    .MultiLine = True
    RemoveExtraSpace = .Replace(inVal, " ")
End With

如果您希望保留换行符,请将模式更改为.Pattern = "[ ]+"(括号以便于阅读)。

答案 1 :(得分:1)

在我的头顶,我使用split功能,然后将这些部分重新组合在一起。

Dim s As String: s = "START TIME: N/A END     TIME: N/A "
sParts = Split(s, " ")
s_wo_xtra_space = ""
for i = lbound(sParts) to ubound(sParts)
    if sParts(i) <> "" then
        s_wo_xtra_space = s_wo_xtra_space & sParts(i) & " "
    end if
next i
s_wo_xtra_space = trim(s_wo_xtra_space)

这假设您仍然希望单词之间有一个空格。

答案 2 :(得分:1)

您可以使用split()拆分空格然后循环并跳过结果数组中的所有空项:

Public Sub RemoveSpaces()

Dim s As String: s = "START TIME: N/A END     TIME: N/A "
Dim str() As String
Dim str1

str = Split(s)
s = ""
For Each str1 In str
    If str1 <> "" Then
        s = s & str1 & " "
    End If
Next str1

s = Trim(s)


Debug.Print s

End Sub

答案 3 :(得分:1)

也许app.Worksheetfunction.Trim?

Public Sub RemoveSpaces()

    Dim s As String: s = "START TIME: N/A END     TIME: N/A "

    s = Application.WorksheetFunction.Trim(s)

    Debug.Print s

End Sub

哦,我看到@Alexis Olson是第一个。

答案 4 :(得分:0)

do until instr(s, "  ") = 0
s = replace(s, "  ", " ")
loop

或者如果你想做一个UDF你可以做这样的事情,然后删除你可以做的双空格s = RmvDblSpc(s)

Function RmvDblSpc(What As String) As String

Do Until InStr(What, "  ") = 0

    What = Replace(What, "  ", " ")

Loop

RmvDblSpc = What

End Function