Hello, I have the code below I found that will attach a range in an Excel file as an email attachment. It is saving a copy of it to my desktop after the email is composed. This is the first time I've done this with only a specified range in the file, but I was wondering if there is a way to have the VBA also delete that file that is created on the desktop, what code that would be, and where that should go?
VBA Code:
Sub Email_File()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set rng = Sheets("Sheet1").Range("A1:Q27").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
With Application
.EnableEvents = False
.ScreenUpdating = False
.Application.DisplayAlerts = False
End With
Dim newBook As Workbook, wFile As String
wFile = ThisWorkbook.Path & "\Transfer-Form.xlsx"
Set newBook = Workbooks.Add
rng.Copy Range("A1")
newBook.SaveAs wFile
newBook.Close False
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.Display
.htmlbody = "<BODY style=font-size:11pt;font-family:Calibri>" & "Please see the attached store transfer. <br>" & "</BODY>" & .htmlbody
.To = Range("AA1").Value
If Evaluate("countif(S1,""Perishable"")") >= 1 Then
.CC = Range("AA2").Value
ElseIf Evaluate("countif(S1,""Grocery"")") >= 1 Then
.CC = Range("AA3").Value
Else
.CC = Range("AA4").Value
End If
.BCC = ""
.Subject = "Store Transfer: " & Range("F10").Value & " || TO || " & Range("F16").Value
.Attachments.Add wFile
'.Send 'or use .Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
.Application.DisplayAlerts = 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