VBA修剪离开领先的白色空间

我试图比较macros中的string,并不总是input数据。 差异归结为领先的空白(即“testing”与“testing”与“testing”)的数量

对于我的macros,这个例子中的三个string应该是等价的。 但是我不能使用Replace,因为string中间的任何空格(例如“test one two three”)应该被保留。 我原以为Trim是应该做的(除去所有尾随空格)。 但是当我在string上使用Trim时,我没有看到有什么区别,而且我肯定在string的前面留下了空格。

所以A)Trim在VBA中做了些什么? B)是否有内置的function,我想要做什么,或者我只需要写一个函数?

谢谢!

TRIM()将删除所有前导空格

 Sub demo() Dim s As String s = " test " s2 = Trim(s) msg = "" For i = 1 To Len(s2) msg = msg & i & vbTab & Mid(s2, i, 1) & vbCrLf Next i MsgBox msg End Sub 

您的数据可能包含不可见的字符,但也不是空格。

正如加里的学生所暗示的那样,angular色不是32,实际上是160.现在我是一个简单的人,白色空间就是白色空间。 因此,根据该视图,我创build了以下函数,它将删除所有不实际显示的Unicode字符(即非特殊字符,非字母数字)。 该function如下:

 Function TrueTrim(v As String) As String Dim out As String Dim bad As String bad = "||127||129||141||143||144||160||173||" 'Characters that don't output something 'the human eye can see based on http://www.gtwiki.org/mwiki/?title=VB_Chr_Values out = v 'Chop off the first character so long as it's white space If v <> "" Then Do While AscW(Left(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Left(out, 1)) & "||") <> 0 'Left(out, 1) = " " Or Left(out, 1) = Chr(9) Or Left(out, 1) = Chr(160) out = Right(out, Len(out) - 1) Loop 'Chop off the last character so long as it's white space Do While AscW(Right(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Right(out, 1)) & "||") <> 0 'Right(out, 1) = " " Or Right(out, 1) = Chr(9) Or Right(out, 1) = Chr(160) out = Left(out, Len(out) - 1) Loop End If 'else out = "" and there's no processing to be done 'Capture result for return TrueTrim = out End Function 

在没有看到代码的情况下很难知道,但是也可以使用Application.WorksheetFunction.Clean()方法和Trim()方法来删除不可打印的字符。

MSDN参考页面WorksheetFunction.Clean()

为什么不尝试使用Instr函数呢? 像这样的东西

 Function Comp2Strings(str1 As String, str2 As String) As Boolean If InStr(str1, str2) <> 0 Or InStr(str2, str1) <> 0 Then Comp2Strings = True Else Comp2Strings = False End If End Function 

基本上你正在检查如果string1包含string2或string2包含string1。 这将始终有效,而且您不必修剪数据。

VBA的修剪function仅限于处理空间。 它将删除string的开头和结尾处的空格。

为了处理像换行符和制表符这样的东西,我总是导入Microsoft VBScript RegEx库,并用它来replace空格字符。

在您的VBA窗口中,转到工具,参考,查找Microsoft VBScript正则expression式5.5。 检查它并点击确定。

然后你可以创build一个相当简单的function来修剪所有的空白空间,而不仅仅是空格。

 Private Function TrimEx(stringToClean As String) Dim re As New RegExp ' Matches any whitespace at start of string re.Pattern = "^\s*" stringToClean = re.Replace(stringToClean, "") ' Matches any whitespace at end of string re.Pattern = "\s*$" stringToClean = re.Replace(stringToClean, "") TrimEx = stringToClean End Function