Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 通过mailitem正文循环不工作_Vba_Loops_Outlook - Fatal编程技术网

Vba 通过mailitem正文循环不工作

Vba 通过mailitem正文循环不工作,vba,loops,outlook,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

我需要在电子邮件正文中找到一个字符串。 我要查找的单词通常显示在正文的邮件项中,如下所示:

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

<>任何帮助都是值得赞赏的。

< P>你可以考虑使用Word对象模型来完成任务。Inspector类的WordEditor属性返回表示消息体的文档类的实例。有关更多信息,请参阅。例如,原始草图:

  mail.GetInspector().WordEditor

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

我想你是对的。Chr$(160)代表什么?如果我写…,它会起作用吗Chr$(160)?字符160是不间断空格。你在HTML中经常看到它,但在使用字符32的普通文本文件中却看不到——这是你习惯使用的空间。您可以简单地将Chr$(160)添加到代码中,但我想我会向您展示一种不同的方式。很高兴它起作用了。