【发布时间】:2018-09-13 12:36:30
【问题描述】:
我目前正在编写一段代码,每天发送一封电子邮件,其中包含作为附件的 excel 文件,以及将活动工作表嵌入到电子邮件正文中。我被要求找出是否有可能让 VBA 的嵌入式组件适应包括新的单元格范围。
所以,例如。在一张工作表上,它将包含当天交易活动的数据。如果我想将第 2 天的交易数据添加到同一个工作表中,并且只将该部分嵌入到电子邮件中,是否可以不每次在 VBA 中编辑单元格范围?
我在下面附上了我的代码:
Sub Mail_Sheet_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
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 = "recipient@test.com"
.CC = ""
.BCC = ""
.Subject = "Trades Today" & Date
.HTMLBody = RangetoHTML(rng)
.Attachments.Add ActiveWorkbook.FullName
.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)
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
'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
对此的任何建议将不胜感激。
【问题讨论】:
-
有没有一种明显的方法可以区分一天的数据和第二天的数据?
-
因为您可以通过更改
Set rng = ActiveSheet.UsedRange使其在获取数据的方式上更加智能来轻松地做到这一点。例如,如果您在每天的数据中有一个日期列,则可以将其设置为仅复制今天或昨天的数据 -
我可以在工作簿中添加一个日期列来做到这一点。我需要如何更改代码才能做到这一点?
-
感谢@Marcucciboy2