从vba中的string的开头和结尾删除空格

我已经写了这个函数来删除string的开始和结束空白,任何想法,为什么它不工作?

Public Function PrepareString(TextLine As String) Do While Left(TextLine, 1) = " " ' Delete any excess spaces TextLine = Right(TextLine, Len(TextLine) - 1) Loop Do While Right(TextLine, 1) = " " ' Delete any excess spaces TextLine = Left(TextLine, Len(TextLine) - 1) Loop PrepareString = TextLine End Function 

这个怎么样。 请注意使用Worksheetfunction.Trim删除Application.Trim没有的多个空格。

 Option Explicit Dim oRegex As Object Sub test() Dim dirtyString As String dirtyString = " This*&(*&^% is_ The&^%&^%><><.,.,.,';';'; String " Debug.Print cleanStr(dirtyString) End Sub Function cleanStr(ByVal dirtyString As String) As String If oRegex Is Nothing Then Set oRegex = CreateObject("vbscript.regexp") With oRegex .Global = True 'Allow AZ, az, 0-9, a space and a hyphen - .Pattern = "[^A-Za-z0-9 -]" cleanStr = .Replace(dirtyString, vbNullString) End With cleanStr = WorksheetFunction.Trim(cleanStr) End Function 

我testing了你的function,它在我的机器上工作正常。

你可以使用内置的Trim()函数来为你做这件事,而不是创build一个同样的事情的UDF。

 Trim(TextLine) 

参考: http : //www.techonthenet.com/excel/formulas/trim.php

为什么不呢?

 Public Function PrepareString(TextLine As String) PrepareString = Trim(TextLine) End Function 

Alexandre / slaver113是完全正确的,因此在UDF内部封装内置函数没有任何意义。 我之所以这样做是为了指出如何使你的UDF工作。 在现实生活中,我决不会以这种方式使用UDF。 🙂