如何replaceMS Excel中单元格中单词“单独”之间的空格

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

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

我想用excel VBA来replace单独的单词与下划线之间空格不是单元格中的任何其他空格 ,即

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

我试图从各种来源find解决scheme,但没有find我所需要的。 许多人build议使用

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

但是他们中的任何一个实际上都会replace所有的空格,甚至在数字和单词和/或数字和数字之间。 我严格只需要被replace的词语之间的空格,而不是任何其他的空格。

我将不胜感激,如果有人可以帮助我一个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 

你没有定义什么区别一个单词而不是一个单词 。 下面的代码很容易修改这个定义。 我select将单词定义为一个以字母开头和结尾的序列。 但是,如果这不起作用,其他定义可以被replace:

编辑正则expression式模式和replace代码修改,以解决序列单字符单词的问题。

 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 

鉴于你提供的两个例子:

在这里输入图像说明

你可以试试这个自定义函数。 看看是否有帮助你

 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是要更改的文本