使用VBA从Excel在电子邮件正文中发送表格时如何保持表格格式

时间:2019-10-17 10:54:41

标签: excel vba email

使用VBA将Excel中的表转换为电子邮件正文(而不是图像) 电子邮件正文中的表格应保留在Excel中设置的所有格式

有一段众所周知的代码(在下面复制)可以正常工作(即数字格式不会丢失) 该代码中的注释说它适用于Excel 2000-2010。 我正在使用2013,并且尝试过此代码,它不再保留数字格式。

Function RangetoHTML(Rng As Range)
' Working in Office 2000-2010
Dim FSO As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
 'Application.ScreenUpdating = True

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
Sheets(Rng.Worksheet.Name).Select
Rng.Select
Selection.Copy
Sheets("interface").Select
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1, 2).PasteSpecial Paste:=8
    .Cells(1, 2).PasteSpecial xlPasteValues, , False, False
    .Cells(1, 2).PasteSpecial xlPasteFormats, , False, False
    .Cells(1, 2).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

Excel电子表格中的表格具有以下格式:负数显示为红色,当值恰好为0时显示为“-”而不是“ 0.00”

上面的function / sub首先将表复制到临时工作簿文件中,在该文件中仍保留格式; 但是,当临时文件转换为html文件/电子邮件正文时,格式会丢失 what the table looks like in Excel, showing '-' this is what the email shows 0.00 instead of '-'

0 个答案:

没有答案