通过mailitem身体循环不工作

时间:2015-04-28 13:23:42

标签: vba loops outlook

我需要在电子邮件正文中找到一个字符串。 我正在寻找的这个词通常会显示在正文的邮件项目中:

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) = " "

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

你可能有一个看起来像空格的特殊角色,但却没有。我的猜测是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

答案 1 :(得分:0)

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

  mail.GetInspector().WordEditor