简单地说:VBA 中的字符串处理函数确实有效。如果您的字符串在输入字符串的开头或结尾有空格字符(特别是代码点为 32 的字符),那么它们将被删除。
“固定长度”字符串只有在您使用特殊语法明确声明它们时才存在:
Dim eightCharString As String(8) ' This is a fixed-length string
VBA 字符串函数都不返回固定长度的字符串。因此,除非您CString
使用上述表示法声明为固定长度的字符串,否则这不是问题。
Logically the only possibility is that the characters you think are spaces are not in fact spaces. A highly likely candidate in an email is that they are HTML non-breaking space characters, or code point 0xA0 (decimal 160). By far the easiest way to replace multiple characters in a source string is using a regular expression.
Here is the typical regex-based trim function. The two patterns as constructed below are
Start pattern: "^[\u0009\u0020\u00A0]*"
End pattern: "[\u0009\u0020\u00A0]*$"
If you want to find and remove additional space characters just add their code point values to the list in the function below. For example, to consider line feeds and carriage returns to be spaces that you want to trim, add the code points 10 and 13 to the list.
Code:
Private m_RxTrimStart As RegExp
Private m_RxTrimEnd As RegExp
Public Function RxTrim(ByRef Source As String) As String
' Only create and compile the RegExp objects once
If m_RxTrimStart Is Nothing Then
' A verbose way of constructing the regex object so you
' can see exactly what's going on
Dim spaceCodePoints As Variant, vCodePoint
Dim strSpaceClass As String, strHexPoint As String
' Add additional code points here if desired
spaceCodePoints = Array(9, 32, 160)
strSpaceClass = "["
For Each vCodePoint In spaceCodePoints
' Assemble a four-character hex code point
strHexPoint = Hex$(CLng(vCodePoint))
strHexPoint = String("0", 4 - Len(strHexPoint)) & strHexPoint
strSpaceClass = strSpaceClass & "\u" & strHexPoint
Next
strSpaceClass = strSpaceClass & "]*"
' Start anchor + spaces character class
Set m_RxTrimStart = New RegExp
m_RxTrimStart.Pattern = "^" & strSpaceClass
' Spaces character class + end anchor
Set m_RxTrimEnd = New RegExp
m_RxTrimEnd.Pattern = strSpaceClass & "$"
End If
RxTrim = m_RxTrimEnd.Replace(m_RxTrimStart.Replace(Source, ""), "")
End Function