如何替换单词之间的空格"单独"在MS Excel中的单元格中

时间:2016-10-03 06:14:43

标签: excel vba excel-vba

我在excel中有一个列(示例单元格如下所示):

               ABCD PQRS;Plate;00;2 XYZ MNO;Bracket;02,1

我希望使用excel VBA替换单元格中的空格与下划线和而不是任何其他空格,即

            ABCD_PQRS;Plate;00;2 XYZ_MNO;Bracket;02,1

我尝试从各种渠道寻找解决方案,但未能成功找到我需要的东西。许多人建议使用

             =SUBSTITUTE and Replace(str, "", "_")

但它们中的任何一个实际上都取代了所有空格,即使在数字和数字之间也是如此。单词和/或数字&数字。 我只需要替换单词之间的空格而不是任何其他空格。

如果有人能帮我解决问题的excel VBA代码,我将不胜感激。

提前致谢!

Sub removeSpaces()  
Dim req As String  
Range("$C$1").Activate  
Do While ActiveCell.Value <> ""  
    ActiveSheet.Select  
    '~~ code here to only choose spaces between words and ignore any other spaces
    req = Replace(ActiveCell.Value, " ", "_")  
    ActiveCell.Value = req  
    ActiveCell.Offset(1, 0).Activate  
Loop

End Sub

2 个答案:

答案 0 :(得分:1)

您没有定义单词非单词的区别。该定义很容易在下面的代码中更改。我选择将单词定义为以字母开头和结尾的序列。但是,如果这不起作用,其他定义可以替代:

编辑更改了正则表达式模式和替换代码,以修复连续单字符单词的问题。

Option Explicit
Function Underscore(S As String) As String
    Dim RE As Object
    Const sPat As String = "([A-Za-z])\s+(?=[A-Za-z])"

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .Pattern = sPat
    .ignorecase = True

    Underscore = .Replace(S, "$1_")
End With
End Function

鉴于您提供的两个例子:

enter image description here

答案 1 :(得分:0)

您可以尝试此自定义功能。看看它是否对你有帮助

Function splitText(cellValue As Range)
    Dim arr As Variant
    Dim newText As String
    arr = Split(cellValue.Text, " ")
    For i = 0 To UBound(arr)
        If i = UBound(arr) Then
            If (IsNumeric(Right(newText, 1)) Or IsNumeric(Left(arr(i), 1))) Then
                newText = newText & " " & arr(i)
            Else
                newText = newText & "_" & arr(i)
            End If
        Else
             If i = 0 Or (IsNumeric(Right(newText, 1)) Or IsNumeric(Left(arr(i), 1))) Then
                newText = newText & " " & arr(i)
            Else
                newText = newText & "_" & arr(i)
            End If
        End If
    Next i
    splitText = newText
End Function

将函数放在一个excel单元格中,例如=splitText(B4),其中B4是您要更改的文本