Browse folders to attach files in Outlook mail using VBA Excel [duplicate] - excel

This question already has answers here:
How to add an attachment to an email using VBA in Excel
(2 answers)
Closed 1 year ago.
I am working on an userform in VBA Excel that allows a user to submit their request. The users complete the form then click on the Send button. An Outlook mail will be opened and the completed form is automatically attached.
The users usually have data or/and documents related to the request. I want to add functionality to my userform, which allows them to browse their PC and import the files. When they click on the Send button, these files will be attached to the same mail as the original Excel form.
Below are the codes for my Send button.
Function CreationMail(criticité As String)
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim rng As Range
Set Sheet1 = ThisWorkbook.Sheets("Formulaire")
Set rng = Sheets("Formulaire").Range("C6:D11").SpecialCells(xlCellTypeVisible)
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
End If
Case Excel8:
xFile = ".xls"
xFormat = Excel8
Case xlExcel12:
xFile = ".xlsb"
xFormat = xlExcel12
End Select
FilePath = Environ$("temp") & "\"
FileName = "STATSAE" & "_" & Format(Now, "yymmdd") & "_" & Format(Now, "hhnnss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.To = ";" & ";"
.CC = ""
If criticité = "Haute" Then
.Importance = olImportanceHigh
End If
If criticité = "" Then
.Importance = olImportanceNormal
End If
If criticité = "Faible" Then
.Importance = olImportanceNormal
End If
.Subject = "Request" & Space(1) & FileName
.Attachments.Add Wb2.FullName
.Body = "Please find the requested information" & vbCrLf & "Best Regards"
.HTMLBody = RangetoHTML(rng)
.Display
End With
Wb2.Close
Kill FilePath & FileName & xFile
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
End Function

First of all, you need to do customizations to your form to pick up files that requires to be attached to the email. Then in the code you can repeat the Add method of the Attachments class for each entry the user has chosen. The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
.Attachments.Add Wb2.FullName
.Attachments.Add your_chosen_file

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
'********************************************************

How to Loop Through A Table Column to Filter Another Table to Send Each Filtered Table By Email?

I am trying to:
Use a value from Table A (column - person's name) to filter on Table B in separate sheet
Copy filtered Table B into the body of an email (outlook)
Send outlook email to email address for that recipient (from Table A)
Loop through the process again for the next person in Table A
Example of Table A:
Example of Table B:
So for example for the first iteration
Take Dave Jones from Table A and filter Table B for Dave Jones.
Copy the filtered Table B to the body of a new email
Send to Dave Jones (davejones#davejones.com).
Return to Table A for the next entry, in this case Anne Smith, and do the same. Repeat until the end of Table A.
I made code for setting up an email but this takes the whole worksheet and does not do any filtering. I am unable to work out how to put this loop together for multiple emails:
Sub SendWorkSheet_SENDEMAILS1()
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
On Error Resume Next
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
End If
Case Excel8:
xFile = ".xls"
xFormat = Excel8
Case xlExcel12:
xFile = ".xlsb"
xFormat = xlExcel12
End Select
FilePath = Environ$("temp") & "\"
FileName = Wb.name & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.to = "EMAIL ADDRESS HERE"
.CC = ""
.BCC = ""
.Subject = "Suppliers"
.HTMLBody = "Hi all," & "<br>" & "<br>" & "Please find attached etc. etc." & "<br>" & "<br>" & "Kind regards," & "<br>" & "<br>" & "Sender"
'.Body = ""
.Attachments.Add Wb2.FullName
.Display
'.Send
End With
Wb2.Close
Kill FilePath & FileName & xFile
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
End Sub
I’ve had the need to do the task you describe a number of times in the past, and the following was the solution I came up with. Great credit to Sigma Coding at https://www.youtube.com/watch?v=ZlInSp0-MdU&ab_channel=SigmaCoding
for providing the bulk of the code – the Loop and Filter stuff I added for my own specific application.
For the following to work, you need to enable a couple of references within VBA. In the VBA Editor, select Tools/References & check the boxes ‘Microsoft Outlook 16.0 Object Library’ and ‘Microsoft Word 16.0 Object Library’. If they’re not already checked, you’ll find them listed alphabetically.
The following code suggestion assumes the following:
• The Managers’ list is on Sheet1 and the range they are contained in is called “MyRange”
• The table to filter is on Sheet2 and starts from cell A1
This code works for me – let me know how you go with it.
Option Explicit
Dim Outlook As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim OutInspect As Outlook.Inspector
Dim EmailTo As String
Dim OutWrdDoc As Word.Document
Dim OutWrdRng As Word.Range
Dim OutWrdTbl As Word.Table
Dim rng As Range, c As Range, MyRange As Range, myFilter As String
Sub TestEmail()
For Each c In Sheet1.Range("MyRange")
myFilter = c.Value
EmailTo = c.Offset(0, 1).Value
Sheet2.Range("A1:E1").AutoFilter Field:=2, Criteria1:="=" & myFilter
'ERROR TRAP
If EmailTo = "" Or Sheet2.Cells.SpecialCells(xlCellTypeVisible).Rows.Count = 1 Then
GoTo Missing:
End If
Set rng = Sheet2.Cells.SpecialCells(xlCellTypeVisible)
On Error Resume Next
Set Outlook = GetObject(, "Outlook.Application")
If Err.Number = 429 Then
Set Outlook = New Outlook.Application
End If
Set OutMail = Outlook.CreateItem(olMailItem)
With OutMail
.To = EmailTo
.Subject = "Suppliers"
.Body = "Please find attached etc."
.Display
Set OutInspect = .GetInspector
Set OutWrdDoc = OutInspect.WordEditor
rng.Copy
Set OutWrdRng = OutWrdDoc.Application.ActiveDocument.Content
OutWrdRng.Collapse Direction:=wdCollapseEnd
Set OutWrdRng = OutWrdDoc.Paragraphs.Add
OutWrdRng.InsertBreak
OutWrdRng.PasteExcelTable Linkedtoexcel:=True, wordformatting:=True, RTF:=True
Set OutWrdTbl = OutWrdDoc.Tables(1)
OutWrdTbl.AllowAutoFit = True
OutWrdTbl.AutoFitBehavior (wdAutoFitWindow)
.Send
Application.CutCopyMode = False
Sheet2.AutoFilterMode = False
End With
Missing:
Next c
End Sub

How to insert a table after body of e-mail and before signature?

I am using a below code that is pasting a table from excel to the outlook file. However, right now the table is pasted on the very bottom of the email - after the signature.
What I would like to achieve is to have the table inserted after a word "region." and before "Regards" - so before signature.
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Dim DateString As String
Dim FolderName As String
Dim myOutlook As Object
Dim myMailItem As Object
Dim mySubject As String
Dim myPath As String
Dim i As Integer
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'Prompt for Email Subject
Set outlApp = CreateObject("Outlook.Application")
weeknumber = "Week " & WorksheetFunction.WeekNum(Now, vbMonday)
'mySubject = InputBox("Subject for Email")
For i = 2 To 3
region = Sheets("Sheet1").Cells(i, 5).Value
mySubject = "Overdue Milestones | " & weeknumber & " | " & region
'Copy every sheet from the workbook with this macro
Set Sourcewb = ActiveWorkbook
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = "C:\Users\mxr0520\Desktop\Ignite Reports\Milestones\" & weeknumber
If i < 3 Then
MkDir FolderName
Else
End If
'Copy every visible sheet to a new workbook
Set sh = Sheets(region)
'If the sheet is visible then copy it to a new workbook
If sh.Visible = -1 Then
sh.Copy
'Set Destwb to the new workbook
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
If Sourcewb.Name = .Name Then
MsgBox "Your answer is NO in the security dialog"
GoTo GoToNextSheet
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
End With
'Change all cells in the worksheet to values if you want
If Destwb.Sheets(1).ProtectContents = False Then
With Destwb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
End If
'Save the new workbook, email it, and close it
'Set otlNewMail = outlApp.CreateItem(myMailItem)
Set OutLookApp = CreateObject("Outlook.application")
Set OutlookMailitem = OutLookApp.CreateItem(0)
With OutlookMailitem
.display
End With
Signature = OutlookMailitem.htmlbody
With Destwb
.SaveAs FolderName _
& "\" & Destwb.Sheets(1).Name & FileExtStr, _
FileFormat:=FileFormatNum
End With
myPath = ActiveWorkbook.path & "\" & ActiveWorkbook.Name
With Destwb
.Close False
End With
With OutlookMailitem
.Subject = mySubject
.To = Sheets("Sheet1").Cells(i, 6)
.CC = Sheets("Sheet1").Cells(i, 7)
.htmlbody = "Dear All," & "<br>" _
& "<br>" _
& "Attached please find the list of milestones that are <b>overdue</b> and <b>due in 14 days</b> for " & region & "." & "<br>" & "<br>" & "Regards," & "<br>" _
& "Marek" _
& Signature
.Attachments.Add myPath
Worksheets("Summary").Range("A1:E14").Copy
Set vInspector = OutlookMailitem.GetInspector
Set weditor = vInspector.WordEditor
wEditor.Application.Selection.Start = Len(.body)
wEditor.Application.Selection.End = wEditor.Application.Selection.Start
wEditor.Application.Selection.Paste
.display
End With
Set OutlookMailitem = Nothing
End If
thank you for help in advance!
Probably easiest to do this by creating an .oft (Outlook Email Template) with the message body and a placeholder for "region" and the table. Create the template without a signature, it will be added automatically per your Outlook user settings, later. I create a template like this, and save as .oft:
Then simply create the new mailitem with Set OutlookMailitem = OutlookApp.CreateItemFromTemplate({path to your template.oft}), replace the "region" placeholder, and copy/paste the table to the table placeholder's location.
Option Explicit
Sub foo()
Dim objOutlook As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim wdDoc As Word.Document
Dim tblRange As Word.Range
Dim region As String
' define your Region, probably this is done in a loop...
region = "Region 1"
Set objOutlook = CreateObject("Outlook.Application")
' Create email from the template file // UPDATE WITH YOUR TEMPLATE PATH
Set objMsg = objOutlook.CreateItemFromTemplate("C:\path\to\your\template.oft")
objMsg.Display
Set wdDoc = objOutlook.ActiveInspector.WordEditor
' replace placeholder with region:
wdDoc.Range.Find.Execute "{{REGION PLACEHOLDER}}", ReplaceWith:=region
' in my template, paragraph 5 is the table placeholder, modify as needed:
Set tblRange = wdDoc.Range.Paragraphs(5).Range
tblRange.Text = "" ' remove the placeholder text
' copy the Excel table // modify to refer to your correct table/range
Sheet1.ListObjects(1).Range.Copy
' paste the table into the email
tblRange.PasteExcelTable False, False, False
End Sub
As you can see, the final email contains my default signature (which was not part of the template.oft file).
You can use the following properties to customize the message body:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
The Word Editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. You can find all these ways described in the Chapter 17: Working with Item Bodies in MSDN.
The Outlook object model doesn't provide any property or method for detecting signatures. You parse the message body and try to find such places.
However, when you create a signature in Outlook, three files (HTM, TXT and RTF) are created in the following folders:
Vista and Windows 7/8/10:
C:\Users\<UserName>\AppData\Roaming\Microsoft\Signatures
Windows XP:
C:\Documents and Settings\<UserName>\Application Data\Microsoft\Signatures
Application Data and AppData are hidden folders, change the view in the Windows explorer so it shows hidden files and folders if you want to see the files.
So, you read the content of these files and try to find the corresponding content in the message body. Note, users may type a custom signature in the end of emails.

Export excel table (and graph) as image (linux, php, python, anything...)

maybe I will have luck here.
I have crazy idea. In order to automatize things at work, I would like to know if there is any possibility to create screenshot or image from excel file using script and then send it somewhere. I dont know whether it is possible using Php, or python, or whatever running on Linux.
If you have working solution on Windows - feel free to post it.
And no, I could not found any possible solution on the internet.
I don't know about taking a screen shot but you can always simply duplicate the excel spreadsheet file and sent it as an attachment to an email address you choose (ie change the '.To' file below). If you have Outlook installed on your machine the following should work. It will append the date to the spreadsheet filename before sending it. You'll of course have to go into the macro and change the settings - but you can always use VBA to create a form prompting you for the necessary information:
Sub send_worksheet()
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
On Error Resume Next
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
End If
Case Excel8:
xFile = ".xls"
xFormat = Excel8
Case xlExcel12:
xFile = ".xlsb"
xFormat = xlExcel12
End Select
FilePath = Environ$("temp") & "\"
FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.To = "email.account#gmail.com"
.CC = ""
.BCC = ""
.Subject = "Example of Spreadsheet sent via email"
.Body = "See the attached spreadsheet."
.Attachments.Add Wb2.FullName
.Send
End With
Wb2.Close
Kill FilePath & FileName & xFile
Application.ScreenUpdating = True
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