我正在尝试比较宏中的字符串,但输入的数据并不总是一致。差异归结为前导空白的数量(即“test”与“test”与“test”)
对于我的宏,示例中的三个字符串应该是等效的。但是我不能使用替换,因为字符串中间的任何空格(例如“测试一二三”)都应该保留。我原以为这就是 Trim 应该做的(以及删除所有尾随空格)。但是当我在字符串上使用 Trim 时,我没有看到任何差异,而且字符串前面肯定留下了空白。
那么 A) Trim 在 VBA 中到底做了什么? B)是否有一个内置函数可以实现我想要做的事情,或者我只需要编写一个函数?
谢谢!
最佳答案
正如加里的学生所提到的,这个角色不是 32。实际上是 160。现在我是一个简单的人,空白就是空白。因此,根据该 View ,我创建了以下函数,该函数将删除人眼实际无法显示的所有 Unicode 字符(即非特殊字符、非字母数字)。该函数如下:
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
关于string - VBA 修剪留下前导空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27807802/