从Excel复制多列以保持格式,将其保留到Outlook邮件

时间:2018-07-09 12:09:54

标签: excel-vba excel-2010 outlook-2010 vba excel

我想将邮件发送给Col A中的每个收件人(单独的邮件),col B中的主题,并将数据从Col D发送到Excel中的Col I作为邮件正文。

我找到了以下代码,并且该代码对于电子邮件地址和主题正常工作。

在主体中,它仅从一列中选择数据(Col D)。如何使用格式更新正文中的范围D2:I2?

Option Explicit

Sub Sample()
    Dim OutApp As Object, OutMail As Object
    Dim ws As Worksheet
    Dim i As Long, lRow As Long

    Set OutApp = CreateObject("Outlook.Application")

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            Set OutMail = OutApp.CreateItem(0)

            With OutMail
                .To = ws.Range("B" & i).Value
                .Cc = ""
                .Subject = ws.Range("C" & i).Value
                .Body = ws.Range("D" & i).Value
                .Display

            End With
        Next i
    End With
End Sub

Excel示例数据

Excel Sample Data

1 个答案:

答案 0 :(得分:2)

使用RangeToString从-How can I convert a range to a string (VBA)?

获取.Body的字符串
Function RangeToString(ByVal myRange as Range) as String
    RangeToString = ""
    If Not myRange Is Nothing Then
        Dim myCell as Range
        For Each myCell in myRange
            RangeToString = RangeToString & "," & myCell.Value
        Next myCell
        'Remove extra comma
        RangeToString = Right(RangeToString, Len(RangeToString) - 1)
    End If
End Function

并像这样使用它:

.Body = RangeToString(ws.Range(ws.Cells(2,"D"),ws.Cells(i, "I")))