[英]Exporting data from Excel to Outlook
我在 Excel 中起草了一封電子郵件,其中填充了數據表中的信息。
單元格 A1 到 A4 包含“嗨,希望你做得好”和消息......等。
A5 到 H10 有一個包含信息的表格,而 A11 到 A30 有類似“期待您的回復”的電子郵件內容。
我只想復制 A1:A4 和 A11:A30 的值,但希望 A5:H10 顯示為表格。
此代碼來自 Ron De Bruin。
我下面的代碼以表格格式粘貼所有內容:
Sub Mail()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set rng = ActiveSheet.Range("A1:A24").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.Display
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.HTMLBody = RangetoHTML(rng)
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)
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"
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
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
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=")
TempWB.Close savechanges:=False
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
使用快捷范圍方法[]
常用方法Range("A1").Value = 123
和快捷方法是[A1] = 123
示例
With OutMail
.Display
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.HTMLBody = [A1] & "<BR>" & _
[A2] & "<BR>" & _
[A3] & "<BR>" & _
[A4] & RangetoHTML(rng) & _
[A11] & "<BR>" & _
[A12] & "<BR>" & _
[A13] & "<BR>" & _
[A14] & "<BR>"
' And more [range]
End With
請記住,方括號是對范圍/括號/引號結構的替代,該方法返回對范圍的真實引用,它可以用在等號的任一側。 它可以用於饋送其他功能並且它具有正常范圍的所有方法和屬性。
記住捷徑從來不是最快的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.