且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用VBA删除开头和结尾的空格,但将空格保留在字符串中

更新时间:2023-01-22 19:03:28

您可以使用正则表达式:

You can do this with regular expressions:

Option Explicit
Function trimWhiteSpace(s As String) As String
    Dim RE As Object

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True
    .Pattern = "^\s*(\S.*\S)\s*"
    trimWhiteSpace = .Replace(s, "$1")
End With
End Function

正则表达式的解释

^\s*(\S.*\S)\s*

选项:区分大小写;^ $匹配行间的中断

Options: Case sensitive; ^$ match at line breaks