问题描述
我正在寻找最快的方法来删除字符串中的 [多个] 空格,然后在一个单元格中输出。可以有 1、2、3、X 个空格字符。
*example: "hello world how are you"*
我的过程非常耗时,所以我正在寻找最快的方法,不一定是最简单的方法,但我对 vba 的了解有限。
这是我目前发现的:
Regex Removing blank space from a string '这个对我不起作用,即使我添加了正则表达式引用。我遇到了编译错误。
With New RegExp
.Pattern = "\s+"
.Global = True
RemoveExtraSpace = .Replace(inVal," ")
End With
工作表函数
Application.WorksheetFunction.Trim(s)
EDIT: str = Application.WorksheetFunction.Trim(str) 'seems to work
每个循环一个我认为这个是分裂的,然后在每个单词之间用一个空格重建?
str = Split(s)
s = ""
For Each str1 In str
If str1 <> "" Then
s = s & str1 & " "
End If
Next str1
s = Trim(s)
所以我很困惑。我觉得我应该使用正则表达式。有人想分享他们对此的看法吗? 谢谢!
解决方法
我希望得到你的想法
在目标单元格中按原样写入文本 然后使用这些代码之一替换
Sub ReplaceInColumn()
Columns("C:C").Select ' change your columns as you need
Selection.Replace What:=" ",Replacement:="",LookAt:=xlPart,_
SearchOrder:=xlByRows,MatchCase:=False,SearchFormat:=False,_
ReplaceFormat:=False,FormulaVersion:=xlReplaceFormula2
End Sub
Sub ReplaceInCell()
Range("A2").Select 'chage your cell as you need
Cells.Replace What:=" ",SearchOrder:= _
xlByRows,ReplaceFormat:=False,_
FormulaVersion:=xlReplaceFormula2
End Sub
,
如果你需要通过代码来做,试试这个
Sub ReplaceSpaces()
Dim myWord_ As String
myWord_ = "hello world how are you"
myWord_ = Replace(myWord_," ","")
End Sub