Chr*_*ris 5 excel vba excel-vba
我已经编写了这个函数来从字符串的开头和结尾删除空格,任何想法为什么它不起作用?
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
Run Code Online (Sandbox Code Playgroud)
dan*_*rak 14
我测试了你的功能,它在我的机器上工作正常.
您可以使用Trim()为您执行此操作的内置函数,而不是创建执行相同操作的UDF.
Trim(TextLine)
Run Code Online (Sandbox Code Playgroud)
参考:http://www.techonthenet.com/excel/formulas/trim.php
小智 4
这个怎么样。请注意 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 A-Z, a-z, 0-9, a space and a hyphen -
.Pattern = "[^A-Za-z0-9 -]"
cleanStr = .Replace(dirtyString, vbNullString)
End With
cleanStr = WorksheetFunction.Trim(cleanStr)
End Function
Run Code Online (Sandbox Code Playgroud)