0

我在试图将字符串绑定到我在 Outlook VBA 中需要的内容时遇到了真正的困难。我已经尝试了来自互联网各地的 100 种不同的东西,包括这里。

我使用以下内容:

CString = LTrim$(RTrim$(Mid(itm.Body, InStr(1, itm.Body, CCMark) + Len(CCMark), _
            InStr(InStr(1, itm.Body, CCMark) + Len(CCMark), itm.Body, CCMark) - (InStr(1, itm.Body, CCMark) + Len(CCMark)))))

CCMark = "C/"

但由于邮件正文包含:C/test C/,变量 (CString) 转到“test”。

我尝试过使用带有 Trim、RTrim、LTrim、Trim$、LTrim$ 和 RTrim$ 的第二个变量。此外,我尝试过用双空格和单空格替换。我已经尝试过在互联网上流行的 TrimAll 函数,它试图找到不同的 Chr() 值以及 vbTab 等。这些似乎都不能替代任何东西。

字符串保持不变。

这是固定长度与可变长度(“相当大”)的字符串问题吗?我还没有找到从固定长度转换为变量的方法。传递一个函数没有奏效。

关于如何得出“测试”结果的任何建议?

非常感谢您的帮助。

4

1 回答 1

1

简单地说: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
于 2013-09-29T19:14:39.497 回答