从没有单元格的Excel中发送Outlook邮件

时间:2015-04-27 13:30:20

标签: excel vba email excel-vba outlook

我在下面的VBA代码,它从excel电子表格中的不同单元格生成邮件。问题在于,当我用它来生成电子邮件时,邮件不会像普通的Outlook邮件那样自动适应屏幕。因此,如果我在智能手机屏幕上阅读,那么文字就不适合屏幕了。

发送邮件的宏和选择范围的函数。

Sub Mail_Sheet_Outlook_Body()

Dim rng As Range
Dim StrBody As String
Dim OutApp As Object
Dim OutMail As Object

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With
'add this for the text string
'StrBody = Sheets("Sheet2").Range("A1").Value & "<br>" & _
 '         Sheets("Sheet2").Range("A2").Value & "<br>" & _
  '        Sheets("Sheet2").Range("A3").Value & "<br><br><br>"

Set rng = Nothing
Set rng = ActiveSheet.UsedRange
'You can also use a sheet name
'Set rng = Sheets("YourSheet").UsedRange

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

On Error Resume Next
With OutMail
    .to = "...." ' email adress here


' Worksheets("Sheet2").Range("A1:A18")
    .cc = ""
    .BCC = ""
    .Subject = "The short update"
    '.HTMLBody = StrBody & RangetoHTML(rng)
    .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 Sub


   Function RangetoHTML(rng As Range)
 ' Working in Office 2000-2013
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

1 个答案:

答案 0 :(得分:0)

For Each Row In rng
For Each Column In Row
StrBody = StrBody & " " & Column
Next
StrBody = StrBody & "<br>"
Next

您可能想要上述代码的内容 即使手动输入的表格也不会自动调整 如果您真的想要保留格式,可以考虑将范围导出到形状并将其转换为图片。 Good luck with that.