Excel中的一键式邮件合并

时间:2019-06-03 13:47:21

标签: excel vba mailmerge

我有一个Excel工作簿,其中有四个工作表,分别称为Overview,1、2和3。

在工作表1、2和3的每一个中,单元格S4中都有一个电子邮件地址,而在单元格I8中有一个表格,并且每张表中的长度都是可变的

在工作表概述中,我想有一个按钮,该按钮会自动将每个工作表中的表发送到该工作表的电子邮件地址

Sub Mailing()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim TargetSheet As String
Dim i As Long
Dim StrBodybegin As String
Dim StrBodyend As String
Dim r As Integer
Dim c As Integer
For i = 4 To 5
'To Range("A" & Rows.Count).End(xlUp).Row
TargetSheet = Range("A" & i).Value

With Application.WorksheetFunction
' Set OutApp = CreateObject("Outlook.Application")
' Set OutMail = OutApp.CreateItem(0)

Set rng = Nothing
On Error Resume Next

r = ThisWorkbook.Worksheets(TargetSheet).Range("I19").End(xlDown).Row
Set rng = ThisWorkbook.Worksheets(TargetSheet).Range(I13, Cells(r, 12))
'Set rng = ThisWorkbook.Worksheets(TargetSheet).Range("I13:L55")

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

On Error Resume Next
With OutMail
    .To = ThisWorkbook.Worksheets(TargetSheet).Range("S4").Value
    .CC = ""
    .BCC = ""
    .Subject = ThisWorkbook.Worksheets(TargetSheet).Range("I5").Value
    .HTMLBody = RangetoHTML(rng)
    .Send   'or use .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing

End With
Next i

End Sub


Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

0 个答案:

没有答案