VBA修剪离开领先的空白 [英] VBA Trim leaving leading white space

查看:184
本文介绍了VBA修剪离开领先的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较宏中的字符串,数据并不总是始终输入。差异归结于领先的空白空间(即测试与测试与测试)的数量。

I'm trying to compare strings in a macro and the data isn't always entered consistently. The difference comes down to the amount of leading white space (ie " test" vs. "test" vs. " test")

对于我的宏,例子应该是等同的。但是,我不能使用Replace,因为字符串中间的任何空格(例如test one two three)应该被保留。我以为这是Trim应该做的(以及删除所有的尾随空格)。但是当我使用Trim在字符串上时,我看不出有什么区别,我绝对在字符串前面留有空格。

For my macro the three strings in the example should be equivalent. However I can't use Replace, as any spaces in the middle of the string (ex. "test one two three") should be retained. I had thought that was what Trim was supposed to do (as well as removing all trailing spaces). But when I use Trim on the strings, I don't see a difference, and I'm definitely left with white space at the front of the string.

所以A )Trim真的在VBA做什么? B)有没有内置的功能,我正在努力做什么,还是只需要编写一个函数?

So A) What does Trim really do in VBA? B) Is there a built in function for what I'm trying to do, or will I just need to write a function?

谢谢!

推荐答案

所以,加里的学生讽刺的是,角色不是32.事实上是160.现在我是简单的人,我是空白的是空白的空间。所以根据这个观点,我创建了以下功能,它将删除所有不能真正显示给人眼的Unicode字符(即非特殊字符,非字母数字)。该功能如下:

So as Gary's Student aluded to, the character wasn't 32. It was in fact 160. Now me being the simple man I am, white space is white space. So in line with that view I created the following function that will remove ALL Unicode characters that don't actual display to the human eye (i.e. non-special character, non-alphanumeric). That function is below:

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

这篇关于VBA修剪离开领先的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆