I modified the code here - https://www.extendoffice.com/documents/excel/3560-excel-send-personalized-email.html
If the text in the cell is long, it is truncated.
I tried increasing the application time value to 0.20, but that did nothing. It got truncated at the same point.
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As LongPtr, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As LongPtr
#Else
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#End If
Sub SendEMail()
Dim xEmail As String
Dim xSubj As String
Dim xMsg As String
Dim xURL As String
Dim i As Integer
Dim k As Double
Dim xCell As Range
Dim xRg As Range
Dim xTxt As String
On Error Resume Next
xTxt = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select the data range:", "navneesi", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
For i = 1 To xRg.Rows.Count
' Get the email address
xEmail = xRg.Cells(i, 1)
' Message subject
xSubj = "Validation Assignment"
' Compose the message
xMsg = ""
xMsg = xMsg & "Validation Assignment: " & vbCrLf & vbCrLf
xMsg = xMsg & " Order ID: " & xRg.Cells(i, 2).Text & vbCrLf
xMsg = xMsg & " Marketplace ID: " & xRg.Cells(i, 3).Text & vbCrLf
xMsg = xMsg & " Order Day: " & xRg.Cells(i, 4).Text & vbCrLf
xMsg = xMsg & " Seller ID: " & xRg.Cells(i, 5).Text & vbCrLf
xMsg = xMsg & " Product Code: " & xRg.Cells(i, 6).Text & vbCrLf
xMsg = xMsg & " Item Name: " & xRg.Cells(i, 7).Text & vbCrLf
xMsg = xMsg & " Defect Source: " & xRg.Cells(i, 8).Text & vbCrLf
xMsg = xMsg & " Defect Day: " & xRg.Cells(i, 9).Text & vbCrLf
xMsg = xMsg & " Defect Text: " & xRg.Cells(i, 10).Text & vbCrLf
' Replace spaces with %20 (hex)
xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
' Replace carriage returns with %0D%0A (hex)
xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
' Create the URL
xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
' Execute the URL (start the email client)
ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
' Wait two seconds before sending keystrokes
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"
Next
End Sub
Well, 1390 doesn't seem like any kind of restriction that I have ever heard about. Maybe 255 characters, or a variable-length string of up to approximately 2 billion (2^31) characters, etc. Can you try doing it this way?
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
NOTE:
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Most relevant URL:
https://www.rondebruin.nl/win/s1/outlook/amail6.htm
Parent URL:
https://www.rondebruin.nl/win/s1/outlook/mail.htm
Found a fix. Instead of usingCells(i, 5).Text use Cells(i, 5).Value.
This makes sure the cell content is sent to outlook as it is instead of converting it to text first which gives rise to issues. (The code in the question was also unable to render chinese text.)
Also, instead of executing a mail to url, I included the object library for outlook and declared the object for outlook application and for mail item. Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Related
I'm a novice programmer and I'm making a program that will send individualized emails to merchandisers with a list when they've violated our pricing policies. I've gotten sending the email and filling in most of the merchandiser-specific information to work, but I'm trying to include URL links so they can view their violations in detail.
Different merchants will have different numbers of violations, so I added this while loop at the end so it adds only those URLs that are pertinent to them. This loop is nested inside a For loop to the end of the data.
Do While ((Range("B" & n).Value <> "") And (Range("A" & n).Value = ""))
xMsg = xMsg & xRg.Cells(n, 21) & vbCrLf
n = n + 1
Loop
If the value in B row n is not empty and A row n is it should add the URL from column 21 on row n to the bottom of the message and then stop when those conditions aren't met (when we're at a new merchant).
Currently, it will only return the value for column 21 from the first row and nothing else, despite appearing to loop.
I've ran the debugger to see if the loop isn't incrementing like it should, but that seems to be working. I've also tried formatting it as a Do Until Loop, using Cells(n, 1).Value and Cells(n, 2).Value for the reference addresses and a Do While with one of the conditions and a nested If to create the other. Nothing has worked.
I can include more of my code if that would be helpful. Please excuse any sloppiness in my code (I know there are plenty). I'm an accountant, not a programmer.
Here is the entirety of my code. Full disclosure and in the interest of plagarism, I got the majority of it from Kutools on Extendoffice.com and have just modified it to my needs. I've also edited out the actual text of the email body.
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As LongPtr, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As LongPtr
#Else
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#End If
Sub SendEMail()
'update by Extendoffice 20160506
Dim xEmail As String
Dim xSubj As String
Dim xMsg As String
Dim xURL As String
Dim i As Integer
Dim n As Long
Dim k As Double
Dim xCell As Range
Dim xRg As Range
Dim xTxt As String
On Error Resume Next
xTxt = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select the data range:", "Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
If xRg.Columns.Count <> 21 Then
MsgBox " Regional format error, please check", , "Kutools for Excel"
Exit Sub
End If
For i = 1 To xRg.Rows.Count
n = i + 2
If InStr(1, xRg.Cells(i, 13).Value, "#") > 0 Then
' Get the email address
xEmail = xRg.Cells(i, 13)
' Message subject
xSubj = "MAPP Violation"
' Compose the message
xMsg = ""
xMsg = xMsg & "Text" &vbCrLf
Do While ((Range("B" & n).Value <> "") And (Range("A" & n).Value = ""))
xMsg = xMsg & xRg.Cells(n, 21) & vbCrLf
n = n + 1
Loop
' Replace spaces with %20 (hex)
xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
' Replace carriage returns with %0D%0A (hex)
xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
' Create the URL
xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
' Execute the URL (start the email client)
ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
' Wait two seconds before sending keystrokes
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"
End If
Next
End Sub
Again, I apologize for the sloppiness. I know the formatting is mediocre and I can make the Do While Loop as a separate sub and call it. I learned basic C++ five years ago and haven't retained much of my knowledge or etiquette. I wasn't planning on anyone else seeing my code so I wasn't going to clean it up until I got it working.
Currently, it's set up so you select the total data range for it to look at. I've kept it that way so I could test it without sending tons of emails to unsuspecting victims. Once I have it working I'll change xRg to be the last populated row and column.
Here's what the data I'm using looks like. I've edited the merchant information to protect their privacy.
enter image description here
Suggested fix:
Sub SendEMail()
Dim xEmail As String, xSubj As String, xMsg As String, xURL As String
Dim i As Long, n As Long, k As Double
Dim xRg As Range
Dim xTxt As String
On Error Resume Next
xTxt = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Please select the data range:", _
"Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
If xRg.Columns.Count <> 21 Then
MsgBox " Regional format error, please check", , "Kutools for Excel"
Exit Sub
End If
For i = 1 To xRg.Rows.Count
If InStr(1, xRg.Cells(i, 13).Value, "#") > 0 Then
xEmail = xRg.Cells(i, 13) 'Get the email address
xSubj = "MAPP Violation" 'Message subject
xMsg = "Text" & vbCrLf
n = i + 2
'### use xRg.Cells() not Range() here...
Do While xRg.Cells(n, "B").Value <> "" And xRg.Cells(n, "A").Value = ""
xMsg = xMsg & xRg.Cells(n, 21) & vbCrLf
n = n + 1
Loop
xSubj = Replace(xSubj, " ", "%20") 'Replace spaces with %20 (hex)
xMsg = Replace(xMsg, " ", "%20")
xMsg = Replace(xMsg, vbCrLf, "%0D%0A") 'Replace carriage returns with %0D%0A (hex)
xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg 'Create the URL
'Execute the URL (start the email client)
ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
'Wait two seconds before sending keystrokes
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"
End If
Next i
End Sub
My issue seems to have been a that the URLs were too long and I reached a character limit which caused errors when exporting to Outlook. I ended up rewriting my code in HTML format so I could add the URLs as hyperlinks and that worked.
My table is structured as:
Vendor Consultor CLIENT Date OS Status
test#test.com Andrew NAME 1 25/12/2017 123456 Pend
test#test.com Andrew NAME 2 31/12/2017 789123 Pend
test134#test.com Joseph NAME 3 10/12/2017 654321 Pend
I need to consolidate everything that is pending for the seller "Andrew or Joseph" and send a single email with the "OS" list.
I am using the following code but unsuccessful as it opens a new email for each row of the worksheet:
Sub email()
Dim i As Long
Dim OutApp, OutMail As Object
Dim strto, strcc, strbcc, strsub, strbody As String
Set OutApp = CreateObject("Outlook.Application")
OutApp.Session.Logon
For i = 1 To Range("C5536").End(xlUp).Row
Set OutMail = OutApp.CreateItem(0)
strto = Cells(i, 1)
strsub = "OS - PENDING"
strbody = "Hello," & vbCrLf & vbCrLf & _
"Please, check your pending OS's" & vbCrLf & vbCrLf & _
"Detalhes:" & vbCrLf & _
"Consultor:" & Cells(i, 3) & vbCrLf & _
"Date:" & Cells(i, 4) & vbCrLf & _
"OS:" & Cells(i, 5) & vbCrLf & vbCrLf & _
"Best Regards" & vbCrLf & _
"Team"
With OutMail
.To = strto
.Subject = strsub
.Body = strbody
.Display
End With
On Error Resume Next
Next
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Create a class cVendorline with the following code
Option Explicit
Private mClient As String
Private mDate As Date
Private mOS As String
Public Property Get Client() As String
Client = mClient
End Property
Public Property Let Client(ByVal bNewValue As String)
mClient = bNewValue
End Property
Public Property Get dDate() As Date
dDate = mDate
End Property
Public Property Let dDate(ByVal bNewValue As Date)
mDate = bNewValue
End Property
Public Property Get OS() As String
OS = mOS
End Property
Public Property Let OS(ByVal sNewValue As String)
mOS = sNewValue
End Property
Then put the following code into a module and run Consolidate
Option Explicit
Sub Consolidate()
#If Early Then
Dim emailInformation As New Scripting.Dictionary
#Else
Dim emailInformation As Object
Set emailInformation = CreateObject("Scripting.Dictionary")
#End If
GetEmailInformation emailInformation
SendInfoEmail emailInformation
End Sub
Sub GetEmailInformation(emailInformation As Object)
Dim rg As Range
Dim sngRow As Range
Dim emailAddress As String
Dim vendorLine As cVendorLine
Dim vendorLines As Collection
Set rg = Range("A1").CurrentRegion ' Assuming the list starts in A1 and DOES NOT contain empty row
Set rg = rg.Offset(1).Resize(rg.Rows.Count - 1) ' Cut the headings
For Each sngRow In rg.Rows
emailAddress = sngRow.Cells(1, 1)
Set vendorLine = New cVendorLine
With vendorLine
.Client = sngRow.Cells(1, 3)
.dDate = sngRow.Cells(1, 4)
.OS = sngRow.Cells(1, 5)
End With
If emailInformation.Exists(emailAddress) Then
emailInformation.item(emailAddress).Add vendorLine
Else
Set vendorLines = New Collection
vendorLines.Add vendorLine
emailInformation.Add emailAddress, vendorLines
End If
Next
End Sub
Sub SendInfoEmail(emailInformation As Object)
Dim sBody As String
Dim sBodyStart As String
Dim sBodyInfo As String
Dim sBodyEnd As String
Dim emailAdress As Variant
Dim colLines As Collection
Dim line As Variant
sBodyStart = "Hello," & vbCrLf & vbCrLf & _
"Please, check your pending OS's" & vbCrLf & vbCrLf & _
"Detalhes:" & vbCrLf
For Each emailAdress In emailInformation
Set colLines = emailInformation(emailAdress)
sBodyInfo = ""
For Each line In colLines
sBodyInfo = sBodyInfo & _
"Consultor:" & line.Client & vbCrLf & _
"Date:" & line.dDate & vbCrLf & _
"OS:" & line.OS & vbCrLf
Next
sBodyEnd = "Best Regards" & vbCrLf & _
"Team"
sBody = sBodyStart & sBodyInfo & sBodyEnd
SendEmail emailAdress, "OS - PENDING", sBody
Next
End Sub
Sub SendEmail(ByVal sTo As String _
, ByVal sSubject As String _
, ByVal sBody As String _
, Optional ByRef coll As Collection)
#If Early Then
Dim ol As Outlook.Application
Dim outMail As Outlook.MailItem
Set ol = New Outlook.Application
#Else
Dim ol As Object
Dim outMail As Object
Set ol = CreateObject("Outlook.Application")
#End If
Set outMail = ol.CreateItem(0)
With outMail
.To = sTo
.Subject = sSubject
.Body = sBody
If Not (coll Is Nothing) Then
Dim item As Variant
For Each item In coll
.Attachments.Add item
Next
End If
.Display
'.Send
End With
Set outMail = Nothing
End Sub
I have an e-mail that is generated through Excel with VBA. This e-mail includes two embedded pictures in the body of the e-mail along with the separate hyperlinks to the videos they refer to. The problem is that it isn't recognizing the second picture and just embedding the same picture twice, however the hyperlinks are correct. Below is a sample of my code:
Private Sub SubmitBtn_Click()
Dim Source As Range
Dim Dest As Workbook
Dim wb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim OutApp As Object
Dim OutMail As Object
Dim MemNme As String, Email As String, UsrName As String, domainID As String, pic As String, pic2 As String
Dim Hlink As String, Hlink2 As String
State = Screener.StateBox
If State = "California" Then
If Screener.MktPlcBox = True Then
pic = "websitewithpicture1"
Hlink = "videolink"
count = 1
End If
If Screener.SubsidyBox = True Then
pic2 = "websitewithpicture2"
Hlink2 = "videolink"
count = 2
End If
With OutMail
.To = Email
.CC = ""
.BCC = ""
.Subject = "Helpful Video"
.HTMLBody = "Dear " & MemNme & ",<br><br>" _
& vbNewLine & vbNewLine & "Thank you for speaking with me today about your plan. You have a lot of choices, " _
& " and <b>we appreciate you choosing company</b>. Helping you understand your plan is important to us and I thought this video would be valuable to you.<br><br>" _
& vbNewLine & "<center><a href=" & Hlink & "<img src=cid:" & Replace(pic, " ", " ", "520") & " height =250 width=400></a>" _
& "<a href=" & Hlink2 & "<img src=cid:" & Replace(pic2, " ", " ", "420") & " height =250 width=400></a></center><br>" _
& vbNewLine & vbNewLine & "You can always get additional information at <b>website.com</b> or by calling the number on the back of your card.<br><br>" _
& vbNewLine & vbNewLine & "Thank you,<br>" _
& vbNewLine & UsrName
.Attachments.Add pic, olByValue, 0
.Attachments.Add pic2, olByValue, 0 <--------It doesn't "See" this pic???
' MsgBox "Press ok to create your e-mail"
.Display 'or use .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Unload Me
End Sub
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Sub SendEMail()
Dim Email As String, Subj As String
Dim Msg As String, URL As String
Dim r As Integer, x As Double
For r = 2 To 2000 'data in rows 2-4
' Get the email address
Email = Cells(r, 6)
' Message subject
Subj = "bug"
' Compose the message
Msg = ""
Msg = Msg & "Dear " & Cells(r, 6) & "," & vbCrLf & vbCrLf
Msg = Msg & "Please Validate thebug Waiting on You "
Msg = Msg & Cells(r, 1).Text & "." & vbCrLf & vbCrLf
Msg = Msg & "S" & vbCrLf
Msg = Msg & "RTS"
' Replace spaces with %20 (hex)
Subj = Application.WorksheetFunction.Substitute(Subj, " ", "%20")
Msg = Application.WorksheetFunction.Substitute(Msg, " ", "%20")
' Replace carriage returns with %0D%0A (hex)
Msg = Application.WorksheetFunction.Substitute(Msg, vbCrLf, "%0D%0A")
' Create the URL
URL = "mailto:" & Email & "?subject=" & Subj & "&body=" & Msg
' Execute the URL (start the email client)
ShellExecute 0&, vbNullString, URL, vbNullString, vbNullString, vbNormalFocus
' Wait two seconds before sending keystrokes
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"
Next r
End Sub
help me debug this, its going to infinity loop
kindly I have a two VBA codes one is to save the printed area as PDF with the same name as the workbook is and save file location is Desktop and it works fine
and I do have another code which start outlook new message and take some specific cell value as subject and another value as body.
The problem is I want the code of the new mail to attach that saved PDF file from code 1 and make the subject to be same as PDF file name.
The save pdf code is:
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub
... and the second outlook new email code is :
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Sub SendEMail()
Dim Email As String, Subj As String
Dim Msg As String, URL As String
Email = " "
Subj = "P.O # " & "-" & Cells(9, 5) & "-" & Cells(15, 2) & "-" & Cells(15, 8) & Cells(15, 7)
Msg = " "
Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
'Replace spaces with %20 (hex)
Subj = Application.WorksheetFunction.Substitute(Subj, " ", "%20")
Msg = Application.WorksheetFunction.Substitute(Msg, " ", "%20")
'Replace carriage returns with %0D%0A (hex)
Msg = Application.WorksheetFunction.Substitute(Msg, vbCrLf, "%0D%0A")
'Create the URL
URL = "mailto:" & Email & "?subject=" & Subj & "&body=" & Msg
'Execute the URL (start the email client)
ShellExecute 0&, vbNullString, URL, vbNullString, vbNullString, vbNormalFocus
'Wait two seconds before sending keystrokes
'Application.Wait (Now + TimeValue("0:00:02"))
'Application.SendKeys "%s"
End Sub
I hope I could clarify my problem fine.
Thanks in advance.
You can try this :
It changes the PDF export to a function to get the file path and use it as an argument in the other one.
URL method doesn't works with attachments, so below is some code for Outlook(edited to contain the whole code)
Preparing mail with Outlook (sorry for french comments):
Sub Send_To_Pdf()
Dim PdfPath As String
Dim BoDy As String
BoDy = Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
PdfPath = Save_as_pdf
EnvoiMail Right(PdfPath, InStr(1, StrReverse(PdfPath), "\") - 1), "recepient1#domain.com;recepient2#domain.com", , , BoDy, 1, PdfPath
End Sub
Public Function Save_as_pdf() As String
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Save_as_pdf = sNewFilePath
End Function
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.createitem(0)
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Subject = Subject '"Je suis content"
.To = Destina '"marcel#machin.com;julien#chose.com"
.cc = CCdest '"chef#machin.com;directeur#chose.com"
.bcc = CCIdest '"un.copain#supermail.com;une-amie#hotmail.com"
.BoDy = BoDyTxt
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i) '"C:\Mes Documents\Zoulie Image.gif"
Next i
End If
.display
'.send '.Attachments.Add ActiveWorkbook.FullName
End With '?plusieurs?MonMessage.Attachments.Add "D:\Prof\Janvier\Base clients.mdb"
Set MonOutlook = Nothing
End Sub