遍历 mailitem 正文不工作

Loop through mailitem body not working

我需要在电子邮件正文中找到一个字符串。 我要找的词通常是这样显示在body的mailitem中的:

Country:                USA

我有这个循环来查找字符串的开头:

Sub GetFirstString()

lBody = ActiveExplorer.Selection.Item(1).Body
lWords = "Country"

If InStr(1, lBody, lWords) > 0 Then
    Do While Mid(lBody, (InStr(1, lBody, lWords) + Len(lWords) + j), 1) = " " Or _
             Mid(lBody, (InStr(1, lBody, lWords) + Len(lWords) + j), 1) = ":"
        j = j + 1
    Loop
lBeginning = J

Else
    MsgBox "No results"
End If

End Sub   

我一定是漏掉了什么,因为即使达到条件,代码也会一直退出循环。示例:当前字符串是“”,但由于第一个条件它应该继续时它总是退出循环:

Mid(lBody, (InStr(1, lBody, lWords) + Len(lWords) + j), 1) = " "

感谢任何帮助。

您可以考虑使用 Word 对象模型来完成这项工作。 Inspector class returns 的 WordEditor 属性 代表消息正文的 Document class 实例。有关详细信息,请参阅 Chapter 17: Working with Item Bodies。例如,原始草图:

  mail.GetInspector().WordEditor

您可能有一个看起来像 space 但实际上不是的特殊字符。我猜是 Chr$(160)。这是一个重写,将隔离消息的美国部分。

Public Sub GetFirstString()

    Dim sBody As String
    Dim sMsg As String
    Dim vaSplit As Variant
    Dim vaLines As Variant
    Dim i As Long

    Const sWORDS As String = "Country:"

    sBody = ActiveExplorer.Selection.Item(1).Body

    'Split the body into lines
    vaLines = Split(sBody, vbNewLine)

    'Loop through the lines
    For i = LBound(vaLines) To UBound(vaLines)
        'If the line has the words
        If InStr(1, vaLines(i), sWORDS) > 0 Then

            'split the line on the words
            vaSplit = Split(vaLines(i), sWORDS)

            'Get rid of any spaces
            sMsg = Replace(vaSplit(UBound(vaSplit)), Space(1), vbNullString)

            'Get rid of any special characters
            sMsg = Replace(sMsg, Chr$(160), vbNullString)

            'Once found, exit the loop because we only want the first one
            Exit For
        Else
            sMsg = "No results"
        End If
    Next i

    MsgBox sMsg

End Sub