2
我有一個自動運行的vba代碼,在處理完它發送的數據後,它將發送Outlook郵件正文中的輸出表。VBA自動運行時的格式問題
我面對的問題是,在Outlook中檢查此電子郵件的用戶能夠以正確的格式查看錶格,但是如果在他們的Gmail帳戶中查看相同的郵件,他們將無法看到格式和外觀像純文本。
但是,如果我手動運行宏,這個問題不會發生。它只在宏自動運行時發生。
Dim OutApp As Object
Dim OutMail As Object
Dim mailid As String
Dim Excelsheet As String
Dim rng As Range
Dim StrBody As String
Dim excelfile As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
Set rng = Sheets("Report").Range("B4:W55").SpecialCells(xlCellTypeVisible)
On Error Resume Next
With OutMail
.To = xxxx
.CC = xxxx
.Subject = "xxxx"
.HTMLBody = StrBody & RangetoHTML(rng)
.Send
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)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2010
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
Dim StrBody As String
StrBody = "Dear Team" & "<br>" & "" & "<br>" & _
"Please find Group MTD Report" & "<br><br><br>"
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
您是否嘗試過使用'On Error Resume Next'移除此錯誤?這條線始終是災難的祕訣,因爲它可能會隱藏錯誤,否則您會收到警告。 – Aiken
感謝您的快速恢復。我刪除了上述代碼後試過,沒有得到任何錯誤。 Outlook中的郵件正文仍是完美的,但是在gmail中檢查相同的郵件時會得到格式問題。 –
我有一個代碼「.BodyFormat = olFormatHTML」,但使用此代碼也沒有得到解決方案。任何人請幫助 –