Send sheet via email - excel

I have a workbook called Status report which contains several sheets. I need to send sheet8 (Called tables) via email.
I generated code but it is giving me errors.
Location of file is on desktop.
Option Explicit
Sub EmailWithOutlook()
Dim oApp As Object
Dim oMail As Object
Dim WB As Workbook
Dim FileName As String
Dim wSht As Worksheet
Dim shtName As String
Application.ScreenUpdating = False
ActiveSheet.Copy
Set WB = ActiveWorkbook
FileName = WB.Worksheets(1).Name
Kill "C:\Users\Default\Desktop" & "Status report.xlsm"
On Error GoTo 0
WB.SaveAs FileName:="C:\Users\Default\Desktop" & "Status report.xlsm"
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
.To = "sleepyyx#gmail.com"
.Subject = "Test workbook"
.body = "Hello, could you please check workbook" & vbCrLf & vbCrLf & _
"I attached you file"
.Attachments.Add WB.FullName
.Display
End With
WB.ChangeFileAccess Mode:=xlReadOnly
Kill WB.FullName
WB.Close SaveChanges:=False
Application.ScreenUpdating = True
Set oMail = Nothing
Set oApp = Nothing
End Sub

Before you kill a File in Kill "C:\Users\Default\Desktop\" & "Status report.xlsm", you need to check if the file exists :
~~> Check if file exists
If Dir("C:\Users\Default\Desktop\" & "Status report.xlsm") <> "" Then
Kill "C:\Users\Default\Desktop\" & "Status report.xlsm"
End If
And you forget the backslash

You probably are trying to use Filename from the cell.
Consider using a variable for consistency and in case it changes, and make sure you include the backslash between the path and filename.
FileName = WB.Worksheets(1).Name
Dim sFullFile As String
sFullFile = "C:\Users\Default\Desktop\" & FileName
If Dir(sFullFile) <> "" Then Kill sFullFile
WB.SaveAs FileName:=sFullFile
Another thing to note is that if you are saving it as an XLSM then the original format also has to be XLSM, or the SaveAs will error if you don't specify the File Format.
XlFileFormat Enumeration Documentation

Related

VBA FilePicker no longer opening from ThisWork.Path

I have a workbook (located on our network) with a macro enabled so I can email exported PDF worksheets via Outlook every Friday. The exported worksheet PDF gets saved to the same location as the Workbook. Outlook then opens the FilePicker and lets me select the file that I want to attach to the email. For some reason the Filepicker is now not opening to ThisWork.path anymore; it opens to my default MyDocuments located on my native computer. The exported file still saves in the proper spot (located on the network) but the FilePicker just wont open to that location. Now, if I move this Workbook to my direct computer, the FilePicker works as it should. I have not changed anything in the VBA so I don't know why this is all the sudden not working. It worked just last week. Below is the code I believe to be relevant to the issue.
'Creates workpath string
Dim mypath As String, fname As String
mypath = ThisWorkbook.Path
fname = CreateObject("Scripting.FileSystemObject").GetBaseName(ThisWorkbook.Name)
'********************************************************
'Saves PDF with Template Text and Date based on Order Date
Sheets(1).ExportAsFixedFormat 0, mypath & "\" & "TEXT Order Sheet " & Format(Range("D7").Value, "mm-dd-yy")
ActiveSheet.Name = Format(Range("D7").Value, "mm-dd-yy")
'********************************************************
Dim xStrFile As String
Dim xFilePath As String
Dim xFileDlg As FileDialog
Dim xFileDlgItem As Variant
Dim xOutApp As Outlook.Application
Dim xMailOut As Outlook.MailItem
Application.ScreenUpdating = False
Set xOutApp = CreateObject("Outlook.Application")
Set xMailOut = xOutApp.CreateItem(olMailItem)
Set xFileDlg = Application.FileDialog(msoFileDialogFilePicker)
xFileDlg.Filters.Clear
xFileDlg.Filters.Add "pdf files", "*.pdf"
xFileDlg.AllowMultiSelect = True
xFileDlg.InitialFileName = ThisWorkbook.Path
If xFileDlg.Show = -1 Then
'********************************************************
With xMailOut
.Display
.To = "fake#email.com"
.Subject = "TEXT" & Range("D7").Value
.HTMLBody = "<p style='font-family:calibri;font-size:12.0pt'>" & "Here is our TEXT order for the week of " & Range("D7").Value & "." & " Please respond to this email to confirm that you have received the order." & .HTMLBody
For Each xFileDlgItem In xFileDlg.SelectedItems
.Attachments.Add xFileDlgItem
Next xFileDlgItem
.Display
End With
End If
Set xMailOut = Nothing
Set xOutApp = Nothing
Application.ScreenUpdating = True
'********************************************************

send each sheet to each persons via outlook

I have a master sheet and a code to split it into separate sheet based on reviewer names, now i need to send all the splitted sheet to each of the reviewers based on sheet names, example: sheet named raj must be sent to raj#gmail.com, sheet named ravi must be sent to ravi#gmail.com I managed to find a code to send a single sheet via mail, i need help to send all the sheets to respective persons via outlook.
Attaching the code to send a single sheet.
Sub EmailWithOutlook()
Dim oApp As Object
Dim oMail As Object
Dim WB As Workbook
Dim FileName As String
Dim wSht As Worksheet
Dim ShtName As String
Dim CurrDate As String
CurrDate = format(Date, "MM-DD-YY")
Application.ScreenUpdating = False
' Make a copy of the active worksheet
' and save it to a temporary file
Sheets("raj").Activate
ActiveSheet.Copy
Set WB = ActiveWorkbook
FileName = WB.Worksheets(1).Name & " " & CurrDate
On Error Resume Next
Kill "C:\Users\Desktop\workfiles\" & FileName
On Error GoTo 0
WB.SaveAs FileName:="C:\Users\Desktop\workfiles\" & FileName
'Create and show the Outlook mail item
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
'Uncomment the line below to hard code a recipient
.To = "raj#gmail.com"
'Uncomment the line below to hard code a subject
.Subject = "Subject Line"
'Uncomment the lines below to hard code a body
.body = "Hi Raj" & vbCrLf & vbCrLf & _
"Please find the attached file for work"
.Attachments.Add WB.FullName
.Display
End With
'Delete the temporary file
'WB.ChangeFileAccess Mode:=xlReadOnly
'Kill WB.FullName
'WB.Close SaveChanges:=False
'Restore screen updating and release Outlook
Application.ScreenUpdating = True
Set oMail = Nothing
Set oApp = Nothing
End Sub
You can iterate over all worksheets in the workbook in the following way to compose an email for each recipient individually:
Set oApp = CreateObject("Outlook.Application")
For i = 1 To WB.Sheets.Count
Set oMail = oApp.CreateItem(0)
With oMail
.To = WB.Sheets(i).Name & "#gmail.com"
.Subject = "Subject Line"
'Uncomment the lines below to hard code a body
.body = "Hi Raj" & vbCrLf & vbCrLf & _
"Please find the attached file for work"
.Attachments.Add WB.FullName
.Send
End With
Next i
You can read more about that in the following articles that I wrote for the technical blog:
How To: Create and send an Outlook message programmatically
How To: Fill TO,CC and BCC fields in Outlook programmatically
How to create and show a new Outlook mail item programmatically: C#, VB.NET

Getting a run time error 91 when trying to break external links in my workbook

I am working to get the code below to work so when I click a button the workbook will save a temporary copy of the workbook, open a new email in outlook, then attach the temp copy to the email to be sent. Everytime it gets to the 'Break External Links section it throws a run time 91. I have worked on this for hours and I know it is mostlikely simple but I am currently at a loss. Any help is greatly appreciated.
Sub EmailWorkbook()
'PURPOSE: Create email message with ActiveWorkbook attached
Dim SourceWB As Workbook
Dim DestinWB As Workbook
Dim OutlookApp As Object
Dim OutlookMessage As Object
Dim TempFileName As Variant
Dim ExternalLinks As Variant
Dim TempFilePath As String
Dim FileExtStr As String
Dim DefaultName As String
Dim UserAnswer As Long
Dim x As Long
Set SourceWB = ActiveWorkbook
'Check for macro code residing in
If Val(Application.Version) >= 12 Then
If SourceWB.FileFormat = 51 And SourceWB.HasVBProject = True Then
UserAnswer = MsgBox("There was VBA code found in this xlsx file. " & _
"If you proceed the VBA code will not be included in your email attachment. " & _
"Do you wish to proceed?", vbYesNo, "VBA Code Found!")
If UserAnswer = vbNo Then Exit Sub 'Handle if user cancels
End If
End If
'Determine Temporary File Path
TempFilePath = Environ$("temp") & "\"
'Determine Default File Name for InputBox
If SourceWB.Saved Then
DefaultName = Left(SourceWB.Name, InStrRev(SourceWB.Name, ".") - 1)
Else
DefaultName = SourceWB.Name
End If
'Ask user for a file name
TempFileName = Application.InputBox("What would you like to name your attachment? (No Special Characters!)", _
"File Name", Type:=2, Default:=DefaultName)
If TempFileName = False Then Exit Sub 'Handle if user cancels
'Determine File Extension
If SourceWB.Saved = True Then
FileExtStr = "." & LCase(Right(SourceWB.Name, Len(SourceWB.Name) - InStrRev(SourceWB.Name, ".", , 1)))
Else
FileExtStr = ".xlsm"
End If
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
'Save Temporary Workbook
SourceWB.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set DestinWB = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
'Break External Links
ExternalLinks = DestinWB.LinkSources(Type:=xlLinkTypeExcelLinks)
'Loop Through each External Link in ActiveWorkbook and Break it
On Error Resume Next
For x = 1 To UBound(ExternalLinks)
DestinWB.BreakLink Name:=ExternalLinks(x), Type:=xlLinkTypeExcelLinks
Next x
On Error GoTo 0
'Save Changes
DestinWB.Save
'Create Instance of Outlook
On Error Resume Next
Set OutlookApp = GetObject(class:="Outlook.Application") 'Handles if Outlook is already open
Err.Clear
If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(class:="Outlook.Application") 'If not, open Outlook
If Err.Number = 429 Then
MsgBox "Outlook could not be found, aborting.", 16, "Outlook Not Found"
GoTo ExitSub
End If
On Error GoTo 0
'Create a new email message
Set OutlookMessage = OutlookApp.CreateItem(0)
'Create Outlook email with attachment
On Error Resume Next
With OutlookMessage
.Display
.To = ""
.CC = ""
.BCC = ""
.Subject = "RealPage Implementation Template Workbook."
.HTMLBody = "Thank you for your time. The attached file are the templates that we covered during our call." & "<br>" & .HTMLBody
.Attachments.Add DestinWB.FullName
End With
On Error GoTo 0
'Close & Delete the temporary file
DestinWB.Close SaveChanges:=False
Kill TempFilePath & TempFileName & FileExtStr
'Clear Memory
Set OutlookMessage = Nothing
Set OutlookApp = Nothing
'Optimize Code
ExitSub:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub

How can I process the same workbook as control passes from one sub to another?

I am making a macro to take my originfile, SaveAsCopy tempfile, delete some sheets and some columns from tempfile and finally send tempfile by Outlook mail.
My code compiles and runs. It does not work great. It doesn't do any modification: so the deleting stuff in the newly generated tempfile is missing.
This is my code :
Macro Master
Sub run_all()
Call files_mang
Call delete
Call mailing_tempfile
End Sub
Sub files_mang()
' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010,
' Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, Outlook 2010.
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim OrigFileName As String
Dim FileExtStr As String
TempFilePath = "filepathhere"
FileExtStr = ".xlsx"
OrigFileName = TempFilePath & "Suivi interne déploiements OINIS S40" & FileExtStr
TempFileName = "Suivi déploiements OINIS - NOKIA S40" & FileExtStr
Set wb1 = Workbooks.Open(OrigFileName)
Set wb1 = ActiveWorkbook
If Val(Application.Version) >= 12 Then
If wb1.FileFormat = 51 And wb1.HasVBProject = True Then
MsgBox "There is VBA code in this xlsx file. There will" & vbNewLine & _
"be no VBA code in the file you send. Save the" & vbNewLine & _
"file as a macro-enabled (. Xlsm) and then retry the macro.", vbInformation
Exit Sub
End If
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Make a copy of the file.
' If you want to change the file name then change only TempFileName variable.
wb1.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set wb2 = Workbooks.Open(TempFilePath & TempFileName & FileExtStr)
Set wb2 = ActiveWorkbook
End Sub
Sub delete()
Application.DisplayAlerts = False
'Delete columns like intern com ect ...
With Worksheets("Suivi Projet WELDON")
.Columns("R:X").delete
End With
With Worksheets("Suivi projet Highway")
.Columns("T:Z").delete
End With
'Delete non usful sheets for client
Worksheets("SuiviCarteOrange").delete
Worksheets("Cartes Orange En Panne").delete
Application.DisplayAlerts = True
End Sub
Sub mailing_tempfile()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
' Change the mail address and subject in the macro before you run this procedure.
With OutMail
.To = "emailaddresshere"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hello World!"
.Attachments.Add ActiveWorkbook.FullName
' You can add other files by uncommenting the following line.
'.Attachments.Add ("C:\test.txt")
' In place of the following statement, you can use ".Display" to
' display the mail.
.Send
End With
On Error GoTo 0
ActiveWorkbook.Close SaveChanges:=False
' Delete the file.
'Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub

Need to send attachment in XLSX format using CDO mail

Hi Iam using follwing code as a sample to send a mail with attachment via SMTP, but the attachment what it send is in XLSM format i need that to be in XLSX (non macro) format. Kindly help me to fo this.
Option Explicit
'This procedure will mail the whole workbook
'You can 't send a Workbook that is open with CDO.
'That's why it use SaveCopyAs to save it with another name and send that file.
Sub CDO_Mail_Workbook()
'Working in 2000-2007
Dim wb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim iMsg As Object
Dim iConf As Object
' Dim Flds As Variant
Set wb = ActiveWorkbook
If Val(Application.Version) >= 12 Then
If wb.FileFormat = 51 And wb.HasVBProject = True Then
MsgBox "There is VBA code in this xlsx file, there will be no VBA code in the file you send." & vbNewLine & _
"Save the file first as xlsm and then try the macro again.", vbInformation
Exit Sub
End If
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Make a copy of the file/Mail it/Delete it
'If you want to change the file name then change only TempFileName
TempFilePath = Environ$("temp") & "\"
TempFileName = "Copy of " & wb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtStr = "." & LCase(Right(wb.Name, Len(wb.Name) - InStrRev(wb.Name, ".", , 1)))
wb.SaveCopyAs TempFilePath & TempFileName & FileExtStr
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
' iConf.Load -1 ' CDO Source Defaults
' Set Flds = iConf.Fields
' With Flds
' .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "Fill in your SMTP server here"
' .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
' .Update
' End With
With iMsg
Set .Configuration = iConf
.To = "ron#debruin.nl"
.CC = ""
.BCC = ""
.From = """Ron"" <ron#something.nl>"
.Subject = "This is a test"
.TextBody = "This is the body text"
.AddAttachment TempFilePath & TempFileName & FileExtStr
.Send
End With
'If you not want to delete the file you send delete this line
Kill TempFilePath & TempFileName & FileExtStr
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
I think what you'll need to do, is have this code reside in an add-in. That way you aren't trying to send the existing file with code via email.
You are sending workbook which you are running code from so it must be .xlsm and so you send it.
You must either create a copy of your workbook without macros and then send this copy or move your macro to PERSONAL (assuming macro you posted is the only code contained in your workbook)

Resources