带有Excel的Outlook邮件:正文和变量问题

时间:2015-05-11 15:39:07

标签: excel vba outlook-vba

我无法让我的.body文章发挥作用。

我可以在outlook中创建项目。 " To:"和"主题"是正确的,但正文不是。
我可以把它包含在" Hello"到"以下服务项目:"或包括"对于y = 2到LR1"到下一个。我希望它包括两者。我如何连接这两个部分? - 解决了!

If匹配函数应与sht3.range(" B"& y)匹配sht3.range(" C"& i)。在" y"循环,y从2变为49,而变量i应该是常量,直到循环完成。然后它应该移动到下一个我再做一次。这不起作用,因为正文包含i变量y的所有行。 - 解决了!

Sub Test()
Dim OutApp As Object
Dim OutMail As Object

Dim Sht1 As Worksheet
Dim Sht2 As Worksheet
Dim Sht3 As Worksheet

Dim i As Long
Dim y As Long
Dim x As Long

Dim LR1 As Long
Dim LR2 As Long

Set Sht1 = ThisWorkbook.Sheets("Sheet1")
Set Sht2 = ThisWorkbook.Sheets("Sheet2")
Set Sht3 = ThisWorkbook.Sheets("Sheet3")

LR1 = Sht1.Cells(Sht1.Rows.Count, "B").End(xlUp).Row
LR2 = Sht3.Cells(Sht3.Rows.Count, "C").End(xlUp).Row

Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")

On Error GoTo Cleanup

For i = 2 To LR2

If Not IsEmpty(Sht3.Range("C" & i)) Then

Sht3.Activate
Sht3.Range("C" & i).Select

Set OutMail = OutApp.CreateItem(0)
On Error Resume Next

        With OutMail
            .To = Sht3.Range("C" & i).Offset(ColumnOffset:=1)
            .Subject = "OE input sheet " & Sht3.Range("C" & i) & ": Service Delivered = NO"
            .body = "Hello " & ActiveCell.Offset(ColumnOffset:=-1).Value & "." _
                & vbNewLine & vbNewLine & _
                "We have noticed, that you have indicated Service Deliverd = NO, while the service line still contains a value. " _
                & vbNewLine & vbNewLine & _
                "We are referring to the following service lines:" _

                For y = 2 To LR1
                Sht1.Activate
                Sht1.Range("B" & y).Select

                    If Sht1.Range("B" & y) = Sht3.Range("C" & i) Then
                        .body = .body & vbNewLine & ActiveCell.Offset(ColumnOffset:=1).Value
                    End If

                Next y
            .Save
        End With

        On Error GoTo 0
        Set OutMail = Nothing
    End If

Next i

Cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub

提前致谢

1 个答案:

答案 0 :(得分:1)

mailItem的.body属性不会将附加信息附加到正文中,它会完全替换正文中的信息。

因此,当您第一次使用“Hello”部分进行设置时,电子邮件正文包含此信息。当你在循环中再次设置它时,它现在只包含你在循环中设置它的信息。

将循环中的行更新为:

    .body = .body & vbNewLine & ActiveCell.Offset(ColumnOffset:=1).Value

它会将新信息附加到电子邮件正文中。