2012-09-29 70 views
4

我已經寫了這個函數來從字符串的開始和結尾刪除空白,任何想法爲什麼它不工作?從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 
+0

Pearson'site的[cell view addin](http://www.cpearson.com/excel/CellView.htm)將有助於確定有問題的空白。如果它是CHAR(160)'non-breaking-space character,我不會感到驚訝。 – brettdj

回答

3

這個怎麼樣。請注意使用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 
1

爲什麼不是這個?

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

Alexandre/slaver113是絕對正確的,它沒有任何意義在UDF中包裝內置函數。我之所以完成上述工作,是爲了指出如何使您的UDF工作。在現實生活中,我絕不會以這種方式使用UDF。 :)

+0

我認爲它可能不工作,因爲它不是前面的空白字符,也許是標籤或其他東西。是否會刪除除文本字符之外的任何代碼? – Chris

+0

那些不可打印的字符或方形字符? '是否會刪除除文本字符之外的任何代碼? '你想要刪除數值嗎? –

+0

你爲什麼要做這樣的事情?在UDF內部封裝一個內置函數有什麼好處,將參數直接傳遞給內置函數,而不需要事先做任何處理?這對我來說似乎完全沒用。 – ApplePie

13

我測試了你的功能,它在我的機器上工作正常。

您可以使用內置的Trim()函數爲您執行此操作,而不是創建一個執行相同操作的UDF。

Trim(TextLine) 

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

+0

我認爲它可能不工作,因爲它不是前面的空白字符,也許是標籤或其他東西。是否會刪除除文本字符之外的任何代碼? – Chris

相關問題