生成电子邮件时VBA运行时错误438

时间:2017-03-30 09:02:32

标签: vba excel-vba outlook excel

我遇到一个问题,我在尝试在VBA中生成多个电子邮件时遇到运行时错误438。当第F列中的多个单元格为“是”时,第一封电子邮件会生成精美但附加的电子邮件。不生成并发生错误。以下是有问题的代码。帮助表示感谢,谢谢

Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In          ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
If ThisWorkbook.Sheets("Mailinfo").cell.Value Like "?*@?*.?*" And _
   LCase(Cells(ThisWorkbook.Sheets("Mailinfo").cell.Row, "F").Value) = "yes" Then

    Set OutMail = OutApp.CreateItem(0)
    On Error Resume Next
    With OutMail
        .To = cell.Value
        .Subject = "Index Option RFQ"
        .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
        .Importance = 2

        .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"



        'You can add files also like this
        '.Attachments.Add ("C:\test.txt")
        .Display  'Or use Send
    End With
    On Error GoTo 0
    Set OutMail = Nothing
End If
Next cell

1 个答案:

答案 0 :(得分:1)

您的For Each语法错误。它应该采用这种形式(例如)

Dim r as range
For each r in ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
    r.Value = 1
Next r

注意我们如何使用r来表示A1:A10

中的每个单元格
For Each cell In ThisWorkbook.Sheets("Mailinfo").Columns("E").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(cell.Offset(0, 1).Value) = "yes" Then
        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"
            .CC = ThisWorkbook.Sheets("Mailinfo").Range("cc_email").Value
            .Importance = 2

            .HTMLBody = StrBody & RangetoHTML(Rng) & "<br>" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Display  'Or use Send
        End With
        Set OutMail = Nothing
    End If
Next cell

注意:正如@MacroMan在下面指出的那样。您的错误令人困惑,因为您使用On Error Resume Next语句屏蔽以前的错误。以这种方式使用它会带来更多的弊大于利。我的建议永远是专门处理每个错误,而不是掩盖它。