string - VBA 修剪留下前导空白

标签 string excel vba

我正在尝试比较宏中的字符串,但输入的数据并不总是一致。差异归结为前导空白的数量(即“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/

相关文章:

c++ - 在构造函数中初始化常量字符串? C++

php - 连接字符串或使用多个回显参数 : which is faster?

vba - Excel 不会显示工作簿工作表

excel - 在 Excel VBA 中更改为加拿大 (CDN) 法语数字格式

python - 尝试使用字典和 map 转换包含特定文本的行时遇到问题

c# - 如何在 C# 中用单个空格替换多个空格?

excel - 在 Excel Visual Basic 中从 CSV 中删除连续的重复值

Excel:计算值在列中出现的次数

java - Apache POI (excel) 执行 getSheet() 与 createSheet()

VBA 在运行时添加到数组